Access specifiers in C++
A key feature of object-oriented programming is data hiding, which prevents a program's functions from directly accessing the internal representation of a class. Within the class body, sections labeled public, private, and protected are used to specify the restrictions of access to class members.
There can be multiple sections in a class labeled public, protected, or private. Each section remains in effect until another section label or the right closing brace of the class body is encountered. Members and classes are given private access by default.
Syntax
class Test{ public: // public members private: // private members protected: // protected members }
public members
The members of the class that are declared as public are available to everyone, as well as the functions and data members of the class that are declared as public.
You can access the public members of a class from anywhere in the program by using the dot (.) member access operator.
Example
#include <iostream> using namespace std; class Car{ public: int NB_wheels; double speed; int mileage; int Id; void ride(){ cout << "Car " << Id << " is on its way with a speed of " << speed << endl; } }; int main() { Car c1; c1.Id = 1; c1.NB_wheels = 4; c1.speed = 250; c1.mileage = 20000; c1.ride(); return 0; }
Résultat
Car 1 is on its way with a speed of 250
private members
You cannot access a private variable or member function from outside of the class. The only functions that can access private members are class functions and friend functions.
The following program illustrates how we define data in the private section and related functions in the public section in order for them to be called from outside the class.
Example
#includeusing namespace std; class Car{ private: int NB_wheels; double speed; int mileage; int Id; public: void Init(int myid, int mywheels, double myspeed, int mymile){ Id = myid; NB_wheels = mywheels; speed = myspeed; mileage = mymile; } void ride(){ cout << "Car " << Id << " is on its way with a speed of " << speed << endl; } }; int main() { Car c1; c1.Init(1, 4, 250, 20000); c1.ride(); return 0; }
Résultat
Car 1 is on its way with a speed of 250
protected members
There is a subtle difference between the protected access specifier and the private access specifier. The protected access specifier prevents access to class members from outside the class, but allows access to class members by subclasses (derived classes) of the protected class.
In the course on inheritance, we will discuss the "protected" specifier in detail and provide examples.