C++ supports the following access specifiers:
Public: Data members and functions are accessible outside the class.
Private: Data members and functions are not accessible outside the class. The exception is the usage of a friend class.
Protected: Data members and functions are accessible only to the derived classes.
Example:
Describe PRIVATE, PROTECTED and PUBLIC along with their differences and give examples.
class A{
int x; int y;
public int a;
protected bool flag;
public A() : x(0) , y(0) {} //default (no argument) constructor
};
main(){
A MyObj;
MyObj.x = 5; // Compiler will issue a ERROR as x is private
int x = MyObj.x; // Compiler will issue a compile ERROR MyObj.x is private
MyObj.a = 10; // no problem; a is public member
int col = MyObj.a; // no problem
MyObj.flag = true; // Compiler will issue a ERROR; protected values are read only
bool isFlag = MyObj.flag; // no problem