Access Modifiers
In Object Oriented Programming access modifiers are used for data hiding. Access Modifiers or Access Specifiers in a class are used to set the accessibility of the class members. That is, it sets some restrictions on the class members not to get directly accessed by the outside functions.
There are three types of access modifiers defined in C++.
1. Public
2. Private
3. Protected
If we do not specify any access modifiers for the members inside the class then by default the access modifier for the members will be Private.
Let's understand these access modifiers with examples.
1. Public
All the class members declared under public are available to everyone. The data members and member functions declared public can be accessed by other classes too. The public members of a class can be accessed from anywhere in the program.
Example
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
class Myclass
{
public:
int a;
int area()
{
return a*a;
};
};
void main()
{
clrscr();
Myclass My;
My.a=10;
cout<<"Side is:"<<My.a<<"\n";
cout<<"Area is:"<<My.area();
getch();
} |
Output
2. Private
The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.
Example
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
class Myclass
{
private:
int a;
public:
int area(int r)
{
a=r; //Assigning value of r to a as a can't be accessed outside the class
return a*a;
}
};
void main()
{
int x=10;
clrscr();
Myclass My;
//My.a=10; This Will generate error in the code
cout<<"Area is:"<<My.area(x);
getch();
} |
Output
3. Protected
Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.
Example
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Parent
{
protected:
int a;
};
class Child : public Parent
{
public:
void set(int x)
{
a=x;
}
void show()
{
cout<<"a:"<<a;
}
};
void main()
{
int x=20;
clrscr();
//Declaration of child class object
Child Ch;
Ch.set(x);
Ch.show();
getch();
} |
Output