Differences Between Struct and Class in C++
In C++, both struct
and class
are used to define user-defined data types. They are quite similar but have some key differences, especially when it comes to access specifiers and usage conventions. Let’s dive into the differences between them:
Key Differences
Feature | Struct | Class |
---|---|---|
Default Access Specifier | Members are public by default. | Members are private by default. |
Usage Convention | Commonly used for plain data structures. | Commonly used for object-oriented designs. |
Inheritance | Inheritance is public by default. | Inheritance is private by default. |
Member Functions | Can have constructors, destructors, and member functions. | Can have constructors, destructors, and member functions. |
Examples
Example of Struct
struct Person {
std::string name;
int age;
void printDetails() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
int main() {
Person p;
p.name = "Alice";
p.age = 25;
p.printDetails(); // Output: Name: Alice, Age: 25
return 0;
}
In this struct
example, both name
and age
are public by default.
Example of Class
class Person {
std::string name;
int age;
public:
Person(std::string n, int a) : name(n), age(a) {}
void printDetails() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
int main() {
Person p("Bob", 30);
p.printDetails(); // Output: Name: Bob, Age: 30
return 0;
}
In this class
example, name
and age
are private by default and can only be accessed or modified through member functions.
Conclusion
Both struct
and class
in C++ allow you to create custom data types with similar functionality. The key difference lies in the default access specifier:
- Struct members are public by default, and it is generally used for simpler data structures.
- Class members are private by default, making it suitable for complex object-oriented designs where encapsulation is important.
Although they are functionally similar, choosing between a struct
and a class
often comes down to style and the intended use of your code.