![]() |
VOOZH | about |
When a base class is derived by a derived class with the help of inheritance, the accessibility of base class by the derived class is controlled by visibility modes. The derived class doesn’t inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:14:6: error: 'int A::y' is protected
int y;
^
prog.cpp:34:12: error: within this context
cout << b.y << endl;
^
prog.cpp:17:6: error: 'int A::z' is private
int z;
^
prog.cpp:37:12: error: within this context
cout << b.z << endl;
^
There are three types of Visibility modes:
prog.cpp: In function 'int main()':
prog.cpp:14:9: error: 'int A::y' is protected
int y;
^
prog.cpp:37:15: error: within this context
cout << b.y << endl;
^
prog.cpp:17:9: error: 'int A::z' is private
int z;
^
prog.cpp:42:15: error: within this context
cout << b.z << endl;
^
prog.cpp: In function 'int main()':
prog.cpp:11:9: error: 'int A::x' is inaccessible
int x;
^
prog.cpp:33:15: error: within this context
cout << b.x << endl;
^
prog.cpp:14:9: error: 'int A::y' is protected
int y;
^
prog.cpp:37:15: error: within this context
cout << b.y << endl;
^
prog.cpp:17:9: error: 'int A::z' is private
int z;
^
prog.cpp:42:15: error: within this context
cout << b.z << endl;
^
prog.cpp: In function 'int main()':
prog.cpp:11:9: error: 'int A::x' is inaccessible
int x;
^
prog.cpp:33:15: error: within this context
cout << b.x << endl;
^
prog.cpp:14:9: error: 'int A::y' is protected
int y;
^
prog.cpp:37:15: error: within this context
cout << b.y << endl;
^
prog.cpp:17:9: error: 'int A::z' is private
int z;
^
prog.cpp:42:15: error: within this context
cout << b.z << endl;
^
After inheriting a base class with the help of a specific Visibility mode, the members will automatically change its visibility as mentioned above. But inorder to change the visibility after this inheritance, we need to do it manually.
Syntax:
<visibility_mode>:
using base::<member>;
For example:
// inorder to change the visibility of x to public
<public>:
using base::<x>;
Example: Consider a base class containing a public member 'a', protected members 'b' and 'c', and private members 'd' and 'e'. Below program explains how to change the visibility of 'b' from protected to public.
Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:22:9: error: 'int BaseClass::d' is private
int d;
^
prog.cpp:47:26: error: within this context
cout << derivedClass.d << endl;
^