Access Specifiers
Access Specifiers
Public : All Objects of same class can access public members with or without using
member functions from outside the class.
Protected :
All objects of same class can access protected members with only public member
functions from outside the class.
(In Inheritance we will cover it in detail next lectures).
Access level is limited to the containing class or types derived
from the containing class.
Private : All objects of same class can access private members with only
public member functions from outside the class.
#include<iostream.h>
class Student
{
public:
int pub;
protected:
int pro;
private:
int pvt;
public:
void showpub()
{
cout<<pub<<endl;
void setpro(int a)
{
pro=a;
void showpro()
{
cout<<pro<<endl;
}
void setpvt(int a)
{
pvt=a;
void showpvt()
{
cout<<pvt<<endl;
};//end of class
void main()
{
////////////////////accessibility of public data member //////////////
Student first;
first.pub=90; // you can access public data member of class from outside
//the class withoud memebr function
cout<<first.pub<<endl; //90
first.setpub(80); //you can access public data member of class from outside
first.showpub(); // by using public member function ///80
Student second;
/*
second.pro=90; // you can not access protected data member of class from outside
//the class withoud memebr function
cout<<second.pro<<endl; //Erro message---> Student::pro is not accessible in function main
*/
second.setpro(10); //you can access protected data member of class from outside
second.showpro(); // by using public member function ///10
////////////////////accessibility of private data member //////////////
Student third;
third.pvt=90; // you can not access private data member of class from outside
//the class withoud memebr function
cout<<third.pvt<<endl; //Erro message---> Student::pvt is not accessible in function main
third.setpvt(5); //you can access private data member of class from outside
third.showpvt(); // by using public member function ///5
}//end of main
Private functions – only accessible inside that class where they are defined
#include <iostream>
using namespace std;
class smallobj
{
private:
int somedata;
int calcdist(int d)
{
int x;
x = d + 1000;
return x;
public:
int mydata;
void setdata(int d)
{somedata = calcdist(d) + d;}
void showdata()
{cout << "Data is" << somedata << endl;}
};
int main()
{
smallobj s1, s2;
s1.setdata(200);
s1.
//s2.mydata =5;
s1.showdata();
//s2.showdata1();
//cout << "myData is" << s2.mydata << endl;
return 0;
}
Protected functions - only accessible inside that class where they are defined and derived classes