Classes in C++
A class in C++ is a blueprint for creating objects that have data members (attributes) and member functions (methods) to manipulate those data members. It is a user-defined data type that can have access modifiers to control the visibility of its members.
C++ provides three access modifiers that can be used to specify the visibility of the members of a class:
- public: Members declared as public are accessible from anywhere outside the class. They can be accessed by objects of the class and by non-member functions.
- private: Members declared as private are accessible only within the class. They cannot be accessed by objects of the class or by non-member functions.
- protected: Members declared as protected are accessible within the class and its subclasses (derived classes). They cannot be accessed by objects of the class or by non-member functions.
The access modifiers can be used to enforce encapsulation, which is the principle of hiding the implementation details of a class from the outside world. By making the data members private and providing public member functions to access and modify them, we can control the way in which the data is accessed and prevent unwanted modifications.
Here is an example of a class with public and private members:
In this example, the
age data members are declared as public, so they can be accessed from outside the class. The
greet() member function is also declared as public, so it can be called by objects of the class and by non-member functions.
On the other hand, the
password data member is declared as private, so it can only be accessed from within the class. This means that other functions and objects outside the class cannot access it directly.
Using Access Modifiers
Here is an example of how to use the access modifiers:
In this example, we create an object of the
Person class and set its
age data members. We then call the
greet() member function to print out a greeting.
However, if we try to access the
password data member directly, we get a compile-time error because it is declared as private. This shows how access modifiers can be used to enforce encapsulation and prevent unwanted modifications to the data members.