In C++, both struct
and class
are used to define user-defined data types. Although they share many similarities, there are key differences between them that can affect how you design your code. In this tutorial, we will explore the main differences between struct
and class
, discuss when to use each, and provide examples to illustrate their usage.
Default Access Modifiers
One of the primary differences between struct
and class
is the default access modifier for their members. By default, all members of a struct
are public, whereas all members of a class
are private. This means that if you want to create a simple data structure with publicly accessible members, using a struct
might be more convenient.
Inheritance
Another difference between struct
and class
is the default inheritance mode. When inheriting from a struct
, the default mode is public inheritance, whereas when inheriting from a class
, the default mode is private inheritance. This can affect how you design your class hierarchies.
Plain Old Data (POD) Types
A POD type is a type that has no user-declared or inherited constructors, destructors, or copy assignment operators. In C++, it’s common to use struct
for POD types and reserve class
for more complex types with member functions and private data. This convention helps distinguish between simple data structures and more complex classes.
Example Usage
Here are some examples that demonstrate the usage of struct
and class
:
// A simple struct to represent a point in 2D space
struct Point {
int x;
int y;
};
// A class to represent a circle with private data and public methods
class Circle {
private:
double radius_;
public:
Circle(double radius) : radius_(radius) {}
double getArea() { return 3.14 * radius_ * radius_; }
};
In the above example, we use a struct
to represent a simple point in 2D space with publicly accessible members. We use a class
to represent a circle with private data (the radius) and public methods (to calculate the area).
Choosing Between Struct and Class
So, when should you use a struct
versus a class
? Here are some general guidelines:
- Use a
struct
for simple data structures with publicly accessible members. - Use a
class
for more complex types with private data and public methods. - Consider using
struct
for POD types to distinguish them from more complex classes.
Ultimately, the choice between struct
and class
depends on your personal preference, coding style, and the specific requirements of your project. However, by following these guidelines, you can write more readable, maintainable, and efficient code.