- In object oriented programming , access specifiers are used .The access specifier refers to accessibility of the variable in a class . Depending upon the type of access specifier , the accessibility of a variable is decided.
- Public access specifier.
- Private access specifier.
- Protected access specifier.
- Public Access Specifier :
- When public access specifier is written before a variable , then the variable can be publicly accessed i.e the variable can be accessed inside the class as well as outside the class.
#include<iostream>
using namespace std;
class demo
{
public:int i;//local variable of class
public:void fun()//function of class
{
cout<<i;
}
};
int main()
{
demo obj;//object of class
obj.i=10;
obj.fun();
}
- In above example ,' int i ' is the variable and ' fun() ' is the function of class demo and it is accessible in the entire program due to the public access specifier.
- Private Access Specifier :
- When private access specifier is written before class members ( variables and functions ) ,then the class members become private and thus,they can be accessed only inside the class.
#include<iostream>
using namespace std;
class demo
{
private:int i;//local variable of class
private:void fun()//function of class
{
cout<<i;
}
};//end of class
int main()
{
demo obj;//object of class
obj.i=10;//error
obj.fun();//error
}
- In above example , local variable ' int i ' and function ' fun() ' are having private access specifier , so it cannot be accessed outside the class.
Note:-When the class members have no access specifier , then they are private by default.
- Protected Access Specifier :
- When protected access specifier is used , the class members can be accessed inside the same class as well as in a derived class , But it cannot be accessed publicly.
#include<iostream>
using namespace std;
class demo
{
protected:int i;//local variable of class
protected:void fun()//function of class
{
cout<<i;
}
};//end of class
int main()
{
demo obj;//object of class
obj.i=10;//error
obj.fun();//error
}
- In above example , local variable ' int i ' and function ' fun() ' are having protected access specifier , so it cannot be accessed outside the class.
YOU HAVE CREATED NICE POST...
ReplyDeleteThanks.
ReplyDelete