C++ offers possibility to control access to class members and functions by using access specifiers. Access specifiers are used to protect data from misuse.
In the Person class from the previous topic we used only public access specifiers for all data members:
Table of Contents
Types of access specifiers in C++
public
private
protected
Public Specifier
Public class members and functions can be used from outside of a class by any function or other classes. You can access public data members or function directly by using dot operator (.) or (arrow operator-> with pointers).
Protected Specifier
Protected class members and functions can be used inside its class. Protected members and functions cannot be accessed from other classes directly. Additionally protected access specifier allows friend functions and classes to access these data members and functions. Protected data members and functions can be used by the class derived from this class. More information about access modifiers and inheritance can be found in C++ Inheritance
Private Specifier
Private class members and functions can be used only inside of class and by friend functions and classes.
We can modify Person class by adding data members and function with different access specifiers:
class Person { public://access control string firstName;//these data members string lastName;//can be accessed tm dateOfBirth;//from anywhere protected: string phoneNumber;//these members can be accessed inside this class, int salary;// by friend functions/classes and derived classes private: string addres;//these members can be accessed inside the class long int insuranceNumber;//and by friend classes/functions };
Access specifier affects all the members and functions until the next access specifier:
For classes, default access specifier is private. The default access specifier for unions and structs is public.