1. Introduction
In C++ programming, both struct and class are used to define custom data types, but they have some key differences mainly in terms of default access control and inheritance.
2. Key Points
1. The default access specifier in a struct is public, whereas in a class, it is private.
2. Inheritance in struct is public by default, but it's private in a class.
3. Functionally, both can have member variables, member functions, constructors, destructors, and can use inheritance and polymorphism.
4. struct is often used for plain data structures, while class is used for encapsulating data and functions.
3. Differences
struct | class |
---|---|
Default access specifier is public. | Default access specifier is private. |
Default inheritance is public. | Default inheritance is private. |
Generally used for passive data structures with public access. | Used for data encapsulation and complex data structures. |
4. Example
#include <iostream>
using namespace std;
// struct example
struct StructExample {
int data;
StructExample() : data(0) {}
};
// class example
class ClassExample {
int data;
public:
ClassExample() : data(0) {}
int getData() const { return data; }
void setData(int d) { data = d; }
};
int main() {
StructExample se;
cout << "Struct data: " << se.data << endl; // Direct access
ClassExample ce;
ce.setData(5);
cout << "Class data: " << ce.getData() << endl; // Access via member function
return 0;
}
Output:
Struct data: 0 Class data: 5
Explanation:
1. StructExample allows direct access to its member data since its default access is public.
2. ClassExample encapsulates its data, providing access through public member functions getData and setData.
5. When to use?
- Use struct for simpler data structures where encapsulation is not a concern, and direct data access is acceptable.
- Use class for more complex data structures where encapsulation is important, and you need to control access to the data.
Related C++/CPP Posts:
Difference Between Struct and Class in C++
Difference Between Pointer and Reference in C++
Difference Between null and nullptr in C++
Difference Between Array and Vector in C++
Difference Between const and constexpr in C++
Difference Between List and Vector in C++
Difference Between Function Overloading and Operator Overloading in C++
Difference Between Array and List in C++
Difference Between a While Loop and a Do-While Loop in C++
Difference Between new and malloc C++
Virtual Function vs Pure Virtual Function in C++
Compile Time Polymorphism vs Runtime Polymorphism in C++
Difference Between Shallow Copy and Deep Copy in C++
Comments
Post a Comment
Leave Comment