You are on page 1of 8

Access Specifiers

Access Modifiers in c++


It controls the access of variables & methods.
It defines how the members (data members & member functions) of a
class can be accessed.
Access modifiers are used to implement an important aspect of object
oriented programming known as data hiding.
There are three access specifiers in c++
1. Public
2. Private
3. protected
Definition
Public: members can be accessed from outside the class.
Private: members cannot be accessed or view from outside
the class.
Protected: members cannot be accessed from outside the
class, however they can be accessed in inherited classes.
Example of public access specifier
# include <iostream> int main()
Using namespace std; {
Class simple1 { simple1 ob1;
public: ob1.display();
Void display() simple 2 ob2;
{ ob2.show();
cout<< “display function call”; return 0;
} }
};
Class simple 2 {
Public:
Void show()
{
cout<<“show method call”;
}
};
Private access specifier
# include <iostream> int main() { int main()
Using namespace std; class3 ob; {
Class class3 ob.a=10; class3 obj;
{ ob.display(): obj.display(10);
private: return 0; return 0;
int a; } }
public:
display()
{ // display (int b) {
Cout<<“display function”; a=b;
} cout<<“value of a=”<<a;
}; }
};
Difference between public,private & protected
access specifiers
public private protected

1. Public members of a class 1. Private members of a 1.Protected members of a


can be accessible from class can be accessible only class can be accessible for
anywhere within a program within that class and by the class itself and in case of
friend function inheritance, it can also be
accessible for its derived
class
2. Used without inheritance 2. Used without inheritance 2. mainly Used with
inheritance

3. Public keyword is used to 3.Private keyword is used to 3. Protected keyword is used


define public members of a declare private members of a to declare protected members
class class of a class
In Tabular form
Modifiers Within class Derived class Outside class Friend function

public √ √ √ √

private √ × × √

protected √ √ × √
Thanks

You might also like