Access Modifiers in C++

Access modifiers are constructs that define the scope and visibility of members of a class. There are three access modifiers:


Private

Private members are accessible only inside the class and not from any other location outside of the class.

Protected

Protected members are accessible from the class as well as from the child class but not from any other location outside of the class.

Public

Public members are accessible from any location of the program.
class Test

{ 
private:   int x;  public: int y;
void getdata()
{ 
cout<<”Enter x and y”<<endl; 
cin>>x>>y;
}
void display()
{ 
cout<<”x=”<<x<<”y=”<<y<<endl;
} }

void main()
{ 
clrscr(); 
Test p;
p.getdata(); 
cout<<”Enter  value of x”<<endl; 
cin>>p.x;
cout<<”Enter value of y”<<endl; 
cin>
>
p.y; 
getch();
}


Here the statement “cin>>p.x;” generates error because x is private data member because, x is private data member and is not accessible from outside of the class. But the statement “cin>>p.y;” does not generates error because y is public data member and is accessible from everywhere. Thus we can say that use of private access specifier is used to achieve data hiding in class.

Share To:

Arogya Thapa Magar

Post A Comment:

0 comments so far,add yours