C++ Interview Questions
C++ Programming
Embedded SystemsIoTOtherQuestion 10
What are the key differences between 'struct' and 'class' in C++?
Answer:
In C++, both struct
and class
are used to define user-defined data types that can encapsulate data members and member functions. However, there are key differences between them:
-
Default Access Modifier:
- struct: Members of a
struct
are public by default. - class: Members of a
class
are private by default.
struct MyStruct { int x; // public by default }; class MyClass { int x; // private by default };
- struct: Members of a
-
Inheritance Access Specifier:
- struct: Inheritance is public by default.
- class: Inheritance is private by default.
struct BaseStruct {}; struct DerivedStruct : BaseStruct {}; // public inheritance class BaseClass {}; class DerivedClass : BaseClass {}; // private inheritance
-
Use Case:
- struct: Typically used for passive objects with public data members (PODs - Plain Old Data structures).
- class: Used for objects with private data members, encapsulation, and methods to manipulate the data.
-
Encapsulation: While both can encapsulate data and methods,
class
is generally used when encapsulation and data hiding are more crucial. -
Friendship and Member Functions: Both
struct
andclass
can have member functions, constructors, destructors, and friend functions. The use and syntax are identical for both. -
Flexibility: Both can be used interchangeably in many cases, but using
class
can make the code more readable by explicitly conveying the intent of encapsulation and object-oriented design principles.
Example:
struct Point {
int x, y;
Point(int a, int b) : x(a), y(b) {}
void display() const {
std::cout << "Point(" << x << ", " << y << ")\n";
}
};
class Circle {
private:
Point center;
double radius;
public:
Circle(Point c, double r) : center(c), radius(r) {}
void display() const {
std::cout << "Circle with center ";
center.display();
std::cout << " and radius " << radius << "\n";
}
};
int main() {
Point p(1, 2);
Circle c(p, 5.0);
p.display();
c.display();
return 0;
}
In this example, Point
is a struct
with public data members and methods, suitable for a simple data structure. Circle
is a class
with private data members and public methods, demonstrating encapsulation. While the differences are subtle, using class
for more complex objects and struct
for simpler data structures can enhance code clarity and maintainability.