Visibility Modes in C++
Visibility Modes in C++
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
PrivateDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Output
Private cannot be accessed.
Protected = 2
Public = 3
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
ProtectedDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Output
Private cannot be accessed.
Protected = 2
Public = 3
3. Public mode:
When we inherit a derived class from a base class with public
visibility mode, the public members and protected members of the
base class will be inherited as public members and protected
members respectively of the derived class.
#include <iostream>
class X{
private:
int a;
protected:
int b;
public:
int c;
};
class Y : public X{
//As the visibility mode is public the protected members of class X
becomes protected member for class Y and public members of class X becomes
public member for class Y
//protected: int b; inherited from class X
//public: int c; inherited from class X
};
int main()
{
//Only int c can be accessed in main function using Class Y object as
it is public;
Y obj;
std::cout<<obj.c;
return 0;
}
#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;
protected:
int prot = 2;
public:
int pub = 3;
int main() {
PublicDerived object1;
cout << "Private = " << object1.getPVT() << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.pub << endl;
return 0;
}
Output
Private = 1
Protected = 2
Public = 3
Notice that the getPVT() function has been defined inside Base . But
the getProt() function has been defined inside PublicDerived .
This is because pvt , which is private in Base , is inaccessible
to PublicDerived .
However, prot is accessible to PublicDerived due to public inheritance.
So, getProt() can access the protected variable from within PublicDerived .
Accessibility in public Inheritance
private members protected members public members
Accessibility