In C++, structures have more versatility and features than in C programming. In addition to member variables, they can contain member functions, have static data members, support access specifiers (public, protected, and private) and support inheritance. In addition to this, there are some additional features in C++ structure:
Following is the syntax of structure definition in C++.
struct StructureName
{
//attributes and methods
};
struct Student
{
string first_name;
int roll_number
// Constructore to initialize data member
Student(string name, int roll)
{
first_name = name;
roll_number = roll;
}
// Member function inside structure to get first name
string get_name()
{
return first_name;
}
// Member function inside structure get roll number
string get_roll()
{
return roll_number;
}
};
// Driver Program
int main()
{
Student s("mohan", 37);
cout << s.roll_number;
cout << s.get_roll();
cout << s.get_name();
return 0;
}
Since we can have structure members as user-defined variables, therefore, we can have structures within the structure.
struct Base
{
int v1;
};
struct Derived : Base
{
int v2;
};
int main()
{
Derived V;
// Works good because inheritance is public.
V.v1 = 1;
cout << V.v1;
return 0;
}
In C++, a class is a user-defined template or blueprint for an object that specifies the characteristics and behavior of a specific type of object. Essentially, it is a collection of data variables and data methods that define a specific object. For example, a mobile phone is an object with its storage capacity as a data variable and the ability to make calls as a data method.
To create a class in C++, the keyword "struct" is replaced with "class". Here is an example:
class ClassName
{
private:
// private attributes and methods
public:
// public attributes and methods
};
C++ classes have several features in common with structures, including the ability to hold member functions and member variables, support access specifiers, and support inheritance. However, they also support additional object-oriented programming (OOP) concepts.
class Student
{
private:
string first_name;
int roll_number
public:
// Constructore to initialize attributes
Student(string name, int roll)
{
first_name = name;
roll_number = roll;
}
// Member function inside class to get first name
string get_name()
{
return first_name;
}
// Member function inside class get roll number
string get_roll()
{
return roll_number;
}
};
// Driver Program
int main()
{
Student s("mohan", 37);
cout << s.get_roll();
cout << s.get_name();
return 0;
}
In C++, there is technically a difference between structures and classes, although the two are syntactically similar. Some of the main differences include:
Enjoy learning, Enjoy oops!
Subscribe to get well designed content on data structure and algorithms, machine learning, system design, object orientd programming and math.