In C++, both classes and structs are used to define user-defined data types, but they have some key differences in terms of their default member accessibility and their intended use.
The main difference between a class and a struct in C++ is the default member accessibility. In a class, members are private by default, whereas in a struct, members are public by default. However, this can be overridden using access specifiers such as public, protected, and private.
Here’s an example of a class in C++:
class Person {
public:
Person(std::string name, int age) {
this->name = name;
this->age = age;
}
void sayHello() {
std::cout << "Hello, my name is " << name << " and I'm " << age << " years old." << std::endl;
}
private:
std::string name;
int age;
};
And here’s an equivalent example using a struct:
struct Person {
public:
Person(std::string name, int age) {
this->name = name;
this->age = age;
}
void sayHello() {
std::cout << "Hello, my name is " << name << " and I'm " << age << " years old." << std::endl;
}
private:
std::string name;
int age;
};
As you can see, the main difference between the two is the keyword used to define the data type. In practice, however, the choice between using a class or a struct often comes down to the intended use of the data type.
Classes are often used to define complex, object-oriented data types, whereas structs are often used to define simpler data types that are primarily used to group data together. For example, you might use a struct to define a point in 3D space, with x, y, and z coordinates, whereas you might use a class to define a more complex object such as a game character with properties such as health, speed, and position, and methods such as move and attack.
In summary, while classes and structs in C++ are similar in many ways, the main difference between them is their default member accessibility and their intended use. Classes are often used to define more complex object-oriented data types, whereas structs are often used to define simpler data types for grouping data together.