CPP Language / Access Specifiers (Public, Private and Protected)

Access specifier / Access modifier are keywords (private, public and protected internal) to specify the accessibility of a type and its members.

Access Specifiers Members Are Accessible
Public outside the class
Private cannot be accessed (or viewed) from outside the class
Protected cannot be accessed from outside but can be accessed in inherited classes


Examples Programs
Program Output

#include
using namespace std;

class a
{
public:
int x; // Public attribute
private:
int y; // Private attribute
};

int main() {
a aobj;
aobj.x = 25; // Allowed (x is public)
aobj.y = 50; // Not allowed (y is private)
return 0;
}


In function ‘int main()’:
error: ‘int a::y’ is private within this context
aobj.y = 50; // Not allowed (y is private)

#include
using namespace std;
class rectangle
{
private:
double area1()
{ return 2*3; }

public:
double area2()
{ return 2*2*3; }
};

int main()
{
rectangle obj;
cout << "Area1:" << obj.area1();
cout << "Area2:" << obj.area2();
return 0;
}

In function ‘int main()’:
error: ‘double rectangle::area1()’ is private within this context
cout << "Area1:" << obj.area1();



Home     Back