Access Modifiers in C++

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 an error because x is a private data member because x is a private data member and is not accessible from outside of the class. But the statement “cin>>p.y;” does not generate an error because y is a public data member and is accessible from everywhere. Thus we can say that the use of private access specifier is used to achieve data hiding in class.

Comments

Popular posts from this blog

C Program for SCAN Disk Scheduling Algorithm | C Programming

C program to Find Cartesian Product of Two Sets | C programming

C Program To Check The String Is Valid Identifier Or Not | C Programming