Public, Protected and Private Inheritance in C++ Programming


You can declare a derived class from a base class with different access control, i.e., public inheritance, protected inheritance or private inheritance.
#include <iostream>
using namespace std;

class base
{
.... ... ....
};

class derived : access_specifier base
{
.... ... ....
};
Note: Either publicprotected or private keyword is used in place of access_specifier term used in the above code.

Example of public, protected and private inheritance in C++

  1. class base
  2. {
  3. public:
  4. int x;
  5. protected:
  6. int y;
  7. private:
  8. int z;
  9. };
  10. class publicDerived: public base
  11. {
  12. // x is public
  13. // y is protected
  14. // z is not accessible from publicDerived
  15. };
  16. class protectedDerived: protected base
  17. {
  18. // x is protected
  19. // y is protected
  20. // z is not accessible from protectedDerived
  21. };
  22. class privateDerived: private base
  23. {
  24. // x is private
  25. // y is private
  26. // z is not accessible from privateDerived
  27. }
In the above example, we observe the following things:
  • base has three member variables: x, y and z which are publicprotected and private member respectively.
  • publicDerived inherits variables x and y as public and protected. z is not inherited as it is a private member variable of base.
  • protectedDerived inherits variables x and y. Both variables become protected. z is not inherited
    If we derive a class derivedFromProtectedDerived from protectedDerived, variables x and y are also inherited to the derived class.
  • privateDerived inherits variables x and y. Both variables become private. z is not inherited
    If we derive a class derivedFromPrivateDerived from privateDerived, variables x and y are not inherited because they are private variables of privateDerived.

Accessibility in Public Inheritance

Accessibilityprivate variablesprotected variablespublic variables
Accessible from own class?yesyesyes
Accessible from derived class?noyesyes
Accessible from 2nd derived class?noyesyes

Accessibility in Protected Inheritance

Accessibilityprivate variablesprotected variablespublic variables
Accessible from own class?yesyesyes
Accessible from derived class?noyesyes
(inherited as protected variables)
Accessible from 2nd derived class?noyesyes

Accessibility in Private Inheritance

Accessibilityprivate variablesprotected variablespublic variables
Accessible from own class?yesyesyes
Accessible from derived class?noyes
(inherited as private variables)
yes
(inherited as private variables)
Accessible from 2nd derived class?nonono

Comments

Popular posts from this blog

C++ Templates ?

C++ Program to Print Number Entered by User

Educational Website