1. Public Access Specifier.
#include <iostream>
using namespace std;
class Example
{
public:
int num;
void square()
{
cout<<"The square of "<<num <<" is ="<<(num*num)<<endl;
}
};
int main()
{
Example e;
e.num = 10; // we can access “num” directly by class object.
e.square();
return 0;
}
The square of 10 is =100
2. Private Access specifier
/*
* Copyright: @ prodevelopertutorial.com
*/
#include <iostream>
using namespace std;
class Example
{
private:
int num;
};
int main()
{
Example e;
e.num = 10;
}
main.cpp: In function ‘int main()’:
main.cpp:19:7: error: ‘int Example::num’ is private within this context
e.num = 10;
^~~
main.cpp:12:13: note: declared private here
int num;
^~~
3. Protected Access specifier.
/*
* Copyright: @ prodevelopertutorial.com
*/
#include <iostream>
using namespace std;
class Parent
{
protected:
int num;
};
class Derived : public Parent
{
public:
void set_and_display_num(int id)
{
num = id;
cout<<"The number is = "<< num<<endl;
}
};
int main()
{
Derived d;
d.set_and_display_num (10);
}
Output:
The number is = 10
What is the need of Access specifiers and how it will help in data hiding?
In the previous example, we saw that, when a data member is made as public, it can be accessed by creating an object of the class.
For example, we need to create program to check the vote, and the user should be able to vote if the age is greater than 18 years.
If we put the “age” variable in public access specifier, that data can be modified easily by other programmer as shown below:
#include <iostream>
using namespace std;
class Vote{
public:
int age;
void put_vote(int id);
};
void Vote::put_vote(int id)
{
cout<<"You have voted for "<<id<<endl;
}
int main()
{
Vote v;
v.age = 10;
v.put_vote(2);
return 0;
}
Output:
You have voted for 2
But this is not the desired behavior. We need to throw an error message that the age criteria is not met.
Hence we make the data member “age” as private and expose it to the getters and setters function.
There we can do the validation.
Example:
#include <iostream>
using namespace std;
class Vote
{
int age;
public:
void set_age(int age);
void put_vote(int id);
};
void Vote::set_age(int num)
{
if (num > 18)
age = num;
else
{
cout<<"You have entered wrong age exiting..."<<endl;
exit(0);
}
}
void Vote::put_vote(int id)
{
cout<<"You have voted for "<<id<<endl;
}
int main()
{
Vote v;
v.set_age(10);
v.put_vote(2);
return 0;
}
Output:
You have entered wrong age exiting...
This is a simple example, but in real-time there will be numerous dependencies, in that case it will be helpful.