Structures and Classes
Structures and Classes
In C++, both structures and classes are used to define custom data types that can hold data members and member functions. They’re user-defined data types that allow you to encapsulate data and functionality into a single entity. The main difference between structures and classes lies in their default access levels and the way members are accessed.
- Structures:In C++, a structure is a user-defined data type that can hold different types of data members but cannot have member functions (methods).The members of a structure are public by default, meaning they can be accessed directly from outside the structure.
Structures are frequently used for simple data grouping, similar to representing a point in 2D space or holding affiliated variables together.
Illustration:
#include <iostream>
using namespace std;
struct Person {
string name;
int age;
float height;
};
int main() {
Person person1;
person1.name = "Alice";
person1.age = 30;
person1.height = 1.75;
cout << "Name: " << person1.name << endl;
cout << "Age: " << person1.age << endl;
cout << "Height: " << person1.height << " meters" << endl;
return 0;
}
- Classes:A class is also a user-defined data type, but it can have both data members and member functions (methods). By default, the members of a class are private, which means they can only be accessed from within the class or by using getter and setter functions.
Classes allow you to implement data abstraction and encapsulation, hiding the internal implementation details from the outside world.
Illustration:
class Rectangle {
private:
int width;
int height;
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
int getArea() const {
return width * height;
}
};
Usage illustration:
int main() {
Point p;
p.x = 5;
p.y5 = 10;
std::cout << “Point coordinates: (“ << p.x << ”, “ << p.y <<”)” << std::endl;
Rectangle r;
r.setWidth(4);
r.setHeight(6);
std::cout << “Rectangle area: “ << r.getArea() << std::endl;
return 0;
}
In modern C++, the distinction between structures and classes has become less significant. With the default access specifier being ‘class’ for both and the preface of the ‘struct’ keyword for inheritance, you can use either to achieve analogous functionality. Still, using structures for simple data aggregation and classes for more complex objects with behavior remains a common and clear practice.