Structure vs Class in C++
In C++, both structures and classes are used to define user-defined data types, but they have some important differences.
Syntax
// Struct syntax
struct struct_name {
// member variables and/or member functions
};
// Class syntax
class class_name {
// member variables and/or member functions
};
Example
#include <iostream>
using namespace std;
// Struct example
struct Student {
string name;
int rollNo;
float gpa;
};
// Class example
class Car {
public:
string color;
string make;
int year;
};
int main() {
// Struct example usage
Student s{ "John", 12345, 3.5 };
cout << "Name: " << s.name << endl;
cout << "Roll No: " << s.rollNo << endl;
cout << "GPA: " << s.gpa << endl;
// Class example usage
Car c;
c.color = "Red";
c.make = "Ford";
c.year = 2021;
cout << "Color: " << c.color << endl;
cout << "Make: " << c.make << endl;
cout << "Year: " << c.year << endl;
return 0;
}
Output
Name: John
Roll No: 12345
GPA: 3.5
Color: Red
Make: Ford
Year: 2021
Explanation
In the above example, we have defined a struct called "Student" and a class called "Car". Both contain member variables, but the class also has a member function that is not shown in the example.
We create an object of each type and set its member variables. Then, we access the member variables for each object to output its values.
Use
Structures are used to represent simple data types that do not have complex behavior. They are often used to group related variables.
Classes, on the other hand, are used to represent more complex objects that have behavior as well as data. They can contain member functions as well as member variables.
Important Points
- Structures are used to group related variables, while classes are used to represent complex objects that have behavior in addition to data.
- Structures are used to represent simple data types, while classes are used to represent more complex objects.
- Members of a struct are public by default, while members of a class are private by default.
- Both structures and classes have constructors and destructors.
- Classes support inheritance and polymorphism.
Summary
In summary, structures and classes in C++ are used to define user-defined data types, but they have some important differences. Structures are used to group related variables, while classes are used to represent more complex objects that have behavior in addition to data. Classes support inheritance and polymorphism, while structures do not.