What is the difference between public, private, and protected inheritance?
Asked Answered
P

17

1259

What is the difference between public, private, and protected inheritance in C++?

Proline answered 13/5, 2009 at 20:47 Comment(0)
T
1200

To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".

There are three accessors that I'm aware of: public, protected and private.

Let:

class Base {
    public:
        int publicMember;
    protected:
        int protectedMember;
    private:
        int privateMember;
};
  • Everything that is aware of Base is also aware that Base contains publicMember.
  • Only the children (and their children) are aware that Base contains protectedMember.
  • No one but Base is aware of privateMember.

By "is aware of", I mean "acknowledge the existence of, and thus be able to access".

next:

The same happens with public, private and protected inheritance. Let's consider a class Base and a class Child that inherits from Base.

  • If the inheritance is public, everything that is aware of Base and Child is also aware that Child inherits from Base.
  • If the inheritance is protected, only Child, and its children, are aware that they inherit from Base.
  • If the inheritance is private, no one other than Child is aware of the inheritance.
Tamikotamil answered 13/5, 2009 at 20:49 Comment(13)
I'd like to add a few words that visibility in C++ is based on class instead of on object, which means that objects of the same class can access each other's private fields without restriction.Our
If you have a hard time understanding this, read Kirill V. Lyadvinsky's answer, then come back and read this.Caudell
This is just another case that illustrates how, for the most part, inheriting from SomeBase is just like a hardcoded way to compose-in an anonymous member of type SomeBase. This, like any other member, has an access specifier, which exerts the same control on external access.Gammer
@ZheChen if I have objects Tom and Jerry of class Person with private field age how do you access (and modify?) Jerry's age using Tom?Inosculate
On the last line, do you mean "no one other than 'Base' is aware of the inheritance?"Chazan
@ZheChen: The part after 'which means that' is true. The part before is only true for private. protected declarations of the base class are accessible to the descendant object, not class: struct Base { protected: int x; }; struct Desc : Base { Desc(Base& b) { (void)b.x; } }; fails to compile.Minister
I want to add one fundamental difference that in Java all the abstract methods have to be declared public in the derived class/subclass. But in C++ private inheritance the methods can be declared private. Suppose class Controller : private ActionListener { private: int onAction() {...} void setup() {registerActionListener(*this);}} Here (*this) is passed as ActionListener object even if they are declared private.Teredo
Could you illustrate what you mean by "aware of the 'inheritance'"? I can understand "i can access this I cannot access that" but i don't get it when one says "I know that A inherits from B" what am I doing here am I checking the inheritance?Tranquillize
@Gammer "an anonymous member of type SomeBase" it isn't anonymous: it's called Derived::SomeBasePoleax
@ZheChen, if I have two objects: b1 and b2 of the same class Base then how can b1 access (as well as modify) the private members of b2?Revolting
@Revolting It's possible. That can be proved by a simple snippet: repl.it/repls/CarefulPinkSpof#main.cppOur
@ZheChen thanks a lot for sharing the code snippet. I had never thought about this. As now I got your point, just curious, in what type of situations/applications this concept is used? If you have any practical example(s) then please do share. It would help a lot in understanding this concept even better.Revolting
@Revolting Move constructor is probably the most common example of something that access and modifies members of another instance. Copy constructor and comparison operators would often access (but not modify) member of another instance.Meggs
B
1789
class A 
{
    public:
       int x;
    protected:
       int y;
    private:
       int z;
};

class B : public A
{
    // x is public
    // y is protected
    // z is not accessible from B
};

class C : protected A
{
    // x is protected
    // y is protected
    // z is not accessible from C
};

class D : private A    // 'private' is default for classes
{
    // x is private
    // y is private
    // z is not accessible from D
};

IMPORTANT NOTE: Classes B, C and D all contain the variables x, y and z. It is just question of access.

About usage of protected and private inheritance you could read here.

Bebop answered 3/9, 2009 at 11:27 Comment(1)
There is a more detailed explanation with examples : programiz.com/cpp-programming/….Divinity
T
1200

To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".

There are three accessors that I'm aware of: public, protected and private.

Let:

class Base {
    public:
        int publicMember;
    protected:
        int protectedMember;
    private:
        int privateMember;
};
  • Everything that is aware of Base is also aware that Base contains publicMember.
  • Only the children (and their children) are aware that Base contains protectedMember.
  • No one but Base is aware of privateMember.

By "is aware of", I mean "acknowledge the existence of, and thus be able to access".

next:

The same happens with public, private and protected inheritance. Let's consider a class Base and a class Child that inherits from Base.

  • If the inheritance is public, everything that is aware of Base and Child is also aware that Child inherits from Base.
  • If the inheritance is protected, only Child, and its children, are aware that they inherit from Base.
  • If the inheritance is private, no one other than Child is aware of the inheritance.
Tamikotamil answered 13/5, 2009 at 20:49 Comment(13)
I'd like to add a few words that visibility in C++ is based on class instead of on object, which means that objects of the same class can access each other's private fields without restriction.Our
If you have a hard time understanding this, read Kirill V. Lyadvinsky's answer, then come back and read this.Caudell
This is just another case that illustrates how, for the most part, inheriting from SomeBase is just like a hardcoded way to compose-in an anonymous member of type SomeBase. This, like any other member, has an access specifier, which exerts the same control on external access.Gammer
@ZheChen if I have objects Tom and Jerry of class Person with private field age how do you access (and modify?) Jerry's age using Tom?Inosculate
On the last line, do you mean "no one other than 'Base' is aware of the inheritance?"Chazan
@ZheChen: The part after 'which means that' is true. The part before is only true for private. protected declarations of the base class are accessible to the descendant object, not class: struct Base { protected: int x; }; struct Desc : Base { Desc(Base& b) { (void)b.x; } }; fails to compile.Minister
I want to add one fundamental difference that in Java all the abstract methods have to be declared public in the derived class/subclass. But in C++ private inheritance the methods can be declared private. Suppose class Controller : private ActionListener { private: int onAction() {...} void setup() {registerActionListener(*this);}} Here (*this) is passed as ActionListener object even if they are declared private.Teredo
Could you illustrate what you mean by "aware of the 'inheritance'"? I can understand "i can access this I cannot access that" but i don't get it when one says "I know that A inherits from B" what am I doing here am I checking the inheritance?Tranquillize
@Gammer "an anonymous member of type SomeBase" it isn't anonymous: it's called Derived::SomeBasePoleax
@ZheChen, if I have two objects: b1 and b2 of the same class Base then how can b1 access (as well as modify) the private members of b2?Revolting
@Revolting It's possible. That can be proved by a simple snippet: repl.it/repls/CarefulPinkSpof#main.cppOur
@ZheChen thanks a lot for sharing the code snippet. I had never thought about this. As now I got your point, just curious, in what type of situations/applications this concept is used? If you have any practical example(s) then please do share. It would help a lot in understanding this concept even better.Revolting
@Revolting Move constructor is probably the most common example of something that access and modifies members of another instance. Copy constructor and comparison operators would often access (but not modify) member of another instance.Meggs
A
129

Limiting the visibility of inheritance will make code not able to see that some class inherits another class: Implicit conversions from the derived to the base won't work, and static_cast from the base to the derived won't work either.

Only members/friends of a class can see private inheritance, and only members/friends and derived classes can see protected inheritance.

public inheritance

  1. IS-A inheritance. A button is-a window, and anywhere where a window is needed, a button can be passed too.

    class button : public window { };
    

protected inheritance

  1. Protected implemented-in-terms-of. Rarely useful. Used in boost::compressed_pair to derive from empty classes and save memory using empty base class optimization (example below doesn't use template to keep being at the point):

    struct empty_pair_impl : protected empty_class_1 
    { non_empty_class_2 second; };
    
    struct pair : private empty_pair_impl {
      non_empty_class_2 &second() {
        return this->second;
      }
    
      empty_class_1 &first() {
        return *this; // notice we return *this!
      }
    };
    

private inheritance

  1. Implemented-in-terms-of. The usage of the base class is only for implementing the derived class. Useful with traits and if size matters (empty traits that only contain functions will make use of the empty base class optimization). Often containment is the better solution, though. The size for strings is critical, so it's an often seen usage here

    template<typename StorageModel>
    struct string : private StorageModel {
    public:
      void realloc() {
        // uses inherited function
        StorageModel::realloc();
      }
    };
    

public member

  1. Aggregate

    class pair {
    public:
      First first;
      Second second;
    };
    
  2. Accessors

    class window {
    public:
        int getWidth() const;
    };
    

protected member

  1. Providing enhanced access for derived classes

    class stack {
    protected:
      vector<element> c;
    };
    
    class window {
    protected:
      void registerClass(window_descriptor w);
    };
    

private member

  1. Keep implementation details

    class window {
    private:
      int width;
    };
    

Note that C-style casts purposely allows casting a derived class to a protected or private base class in a defined and safe manner and to cast into the other direction too. This should be avoided at all costs, because it can make code dependent on implementation details - but if necessary, you can make use of this technique.

Auxin answered 3/9, 2009 at 16:4 Comment(1)
I think Scott Myers (as much as I like his stuff) has a lot to answer for the general confusion. I now think his analogies of IS-A and IS-IMPLEMENTED-IN-TERMS-OF are in sufficient for what is going on.Titan
G
92

These three keywords are also used in a completely different context to specify the visibility inheritance model.

This table gathers all of the possible combinations of the component declaration and inheritance model presenting the resulting access to the components when the subclass is completely defined.

enter image description here

The table above is interpreted in the following way (take a look at the first row):

if a component is declared as public and its class is inherited as public the resulting access is public.

An example:

 class Super {
    public:      int p;
    private:     int q;
    protected:   int r;
 };

 class Sub : private Super {};

 class Subsub : public Sub {};

The resulting access for variables p, q, r in class Subsub is none.

Another example:

class Super {
    private:     int x;
    protected:   int y;
    public:      int z;
 };
class Sub : protected Super {};

The resulting access for variables y, z in class Sub is protected and for variable x is none.

A more detailed example:

class Super {
private:
    int storage;
public:
    void put(int val) { storage = val;  }
    int  get(void)    { return storage; }
};
int main(void) {
    Super object;

    object.put(100);
    object.put(object.get());
    cout << object.get() << endl;
    return 0;
}

Now lets define a subclass:

class Sub : Super { };

int main(void) {
    Sub object;

    object.put(100);
    object.put(object.get());
    cout << object.get() << endl;
    return 0;
}

The defined class named Sub which is a subclass of class named Super or that Sub class is derived from the Super class. The Sub class introduces neither new variables nor new functions. Does it mean that any object of the Sub class inherits all the traits after the Super class being in fact a copy of a Super class’ objects?

No. It doesn’t.

If we compile the following code, we will get nothing but compilation errors saying that put and get methods are inaccessible. Why?

When we omit the visibility specifier, the compiler assumes that we are going to apply the so-called private inheritance. It means that all public superclass components turn into private access, private superclass components won't be accessible at all. It consequently means that you are not allowed to use the latter inside the subclass.

We have to inform the compiler that we want to preserve the previously used access policy.

class Sub : public Super { };

Don’t be misled: it doesn’t mean that private components of the Super class (like the storage variable) will turn into public ones in a somewhat magical way. Private components will remain private, public will remain public.

Objects of the Sub class may do "almost" the same things as their older siblings created from the Super class. "Almost" because the fact of being a subclass also means that the class lost access to the private components of the superclass. We cannot write a member function of the Sub class which would be able to directly manipulate the storage variable.

This is a very serious restriction. Is there any workaround?

Yes.

The third access level is called protected. The keyword protected means that the component marked with it behaves like a public one when used by any of the subclasses and looks like a private one to the rest of the world. -- This is true only for the publicly inherited classes (like the Super class in our example) --

class Super {
protected:
    int storage;
public:
    void put(int val) { storage = val;  }
    int  get(void)    { return storage; }
};

class Sub : public Super {
public:
    void print(void) {cout << "storage = " << storage;}
};

int main(void) {
    Sub object;

    object.put(100);
    object.put(object.get() + 1);
    object.print();
    return 0;
}

As you see in the example code we a new functionality to the Sub class and it does one important thing: it accesses the storage variable from the Super class.

It wouldn’t be possible if the variable was declared as private. In the main function scope the variable remains hidden anyway so if you write anything like:

object.storage = 0;

The compiler will inform you that it is an error: 'int Super::storage' is protected.

Finally, the last program will produce the following output:

storage = 101
Greenockite answered 7/6, 2015 at 16:56 Comment(3)
First one to mention the lack of a modifier (as in Class : SuperClass) yields private. This is an important piece the others are missing out, along with thorough explanations. +1Flickinger
A protected member on public inheritance becomes private on derived class, right? The table says it is becomes protected?Balaklava
@Balaklava No it says: if a component is declared as protected and its class is inherited as public the resulting access is protected.Greenockite
S
70

It has to do with how the public members of the base class are exposed from the derived class.

  • public -> base class's public members will be public (usually the default)
  • protected -> base class's public members will be protected
  • private -> base class's public members will be private

As litb points out, public inheritance is traditional inheritance that you'll see in most programming languages. That is it models an "IS-A" relationship. Private inheritance, something AFAIK peculiar to C++, is an "IMPLEMENTED IN TERMS OF" relationship. That is you want to use the public interface in the derived class, but don't want the user of the derived class to have access to that interface. Many argue that in this case you should aggregate the base class, that is instead of having the base class as a private base, make in a member of derived in order to reuse base class's functionality.

Shackelford answered 13/5, 2009 at 20:49 Comment(2)
Better say "public: the inheritance will be seen by everyone". protected: the inheritance will only be seen by derived classes and friends", "private: the inheritance will only be seen by the class itself and friends". This is different from your wording, since not only the members can be invisible, but also the IS-A relation can be invisible.Auxin
The one time I used private inheritance was to do Just what Doug T describes i.e "you want to use the public interface in the derived class, but don't want the user of the derived class to have access to that interface". I basically used it to seal off the old interface and expose another one through the derived class.Ewan
T
38
Member in base class : Private   Protected   Public   

Inheritance type :             Object inherited as:

Private            :   Inaccessible   Private     Private   
Protected          :   Inaccessible   Protected   Protected  
Public             :   Inaccessible   Protected   Public
Tartarous answered 9/9, 2010 at 5:25 Comment(1)
This misleading. Private members of a base class behave quite differently from ordinary private class members--they're not accessible from the derived class at all. I think your column of three "Private" should be a column of "Inaccessible". See Kirill V. Lyadvinsky's answer to this question.Undesigning
C
29
  1. Public Inheritance:

    a. Private members of Base class are not accessible in Derived class.

    b. Protected members of Base class remain protected in Derived class.

    c. Public members of Base class remain public in Derived class.

    So, other classes can use public members of Base class through Derived class object.

  2. Protected Inheritance:

    a. Private members of Base class are not accessible in Derived class.

    b. Protected members of Base class remain protected in Derived class.

    c. Public members of Base class too become protected members of Derived class.

    So, other classes can't use public members of Base class through Derived class object; but they are available to subclass of Derived.

  3. Private Inheritance:

    a. Private members of Base class are not accessible in Derived class.

    b. Protected & public members of Base class become private members of Derived class.

    So, no members of Base class can be accessed by other classes through Derived class object as they are private in Derived class. So, even subclass of Derived class can't access them.

Cassino answered 26/5, 2016 at 4:42 Comment(0)
U
20

Public inheritance models an IS-A relationship. With

class B {};
class D : public B {};

every D is a B.

Private inheritance models an IS-IMPLEMENTED-USING relationship (or whatever that's called). With

class B {};
class D : private B {};

a D is not a B, but every D uses its B in its implementation. Private inheritance can always be eliminated by using containment instead:

class B {};
class D {
  private: 
    B b_;
};

This D, too, can be implemented using B, in this case using its b_. Containment is a less tight coupling between types than inheritance, so in general it should be preferred. Sometimes using containment instead of private inheritance is not as convenient as private inheritance. Often that's a lame excuse for being lazy.

I don't think anyone knows what protected inheritance models. At least I haven't seen any convincing explanation yet.

Unconditional answered 3/9, 2009 at 12:34 Comment(4)
Some says an as a relationship. Like using chair as a hammer. Here chair : protected hammerMylan
when using containment instead of private inheritance is not as convenient as private inheritance? Will you please explain it using an example?Laywoman
@Pravasi: If D derives privately from D, it can override virtual functions of B. (If, for example, B is an observer interface, then D could implement it and pass this to functions requiring auch an interface, without everybody being able to use D as an observer.) Also, D could selectively make members of B available in its interface by doing using B::member. Both is syntactically inconvenient to implement when B is a member.Unconditional
@sbi: old one but... containment is a no-go in case of CRTP and/or virtuals (as you correctly described in comment - but that means that it can't be modelled as containment if B has abstract methods and you're not allowed to touch it). protected inheritance I've found useful with a virtual base class and protected ctor: struct CommonStuff { CommonStuff(Stuff*) {/* assert !=0 */ } }; struct HandlerMixin1 : protected virtual CommonStuff { protected: HandlerMixin1() : CommonStuff(nullptr) {} /*...*/ }; struct Handler : HandlerMixin1, ... { Handler(Stuff& stuff) : CommonStuff(&stuff) {} };Minister
S
11
Accessors    | Base Class | Derived Class | World
—————————————+————————————+———————————————+———————
public       |      y     |       y       |   y
—————————————+————————————+———————————————+———————
protected    |      y     |       y       |   n
—————————————+————————————+———————————————+———————
private      |            |               |    
  or         |      y     |       n       |   n
no accessor  |            |               |

y: accessible
n: not accessible

Based on this example for java... I think a little table worth a thousand words :)

Stonedeaf answered 9/5, 2015 at 23:3 Comment(3)
Java has only public inheritanceEpic
This not the topic to speak about java but NO, you're wrong... Follow the link in my answer above for detailsStonedeaf
You mentioned java so it is the topic. And your example handles the specifiers which use in jaca. The question is about the specifiers for inheritance which are not exist in Java an made a difference. If a field in superclass is public and the inheritance is private the field is only acessible inside the subclass. Outside there is no indication if the subclass extends the superclass. But your table explains only the specifiers for field and methods.Epic
P
10

If you inherit publicly from another class, everybody knows you are inheriting and you can be used polymorphically by anyone through a base class pointer.

If you inherit protectedly only your children classes will be able to use you polymorphically.

If you inherit privately only yourself will be able to execute parent class methods.

Which basically symbolizes the knowledge the rest of the classes have about your relationship with your parent class

Prynne answered 3/9, 2009 at 11:27 Comment(0)
G
9

Protected data members can be accessed by any classes that inherit from your class. Private data members, however, cannot. Let's say we have the following:

class MyClass {
    private:
        int myPrivateMember;    // lol
    protected:
        int myProtectedMember;
};

From within your extension to this class, referencing this.myPrivateMember won't work. However, this.myProtectedMember will. The value is still encapsulated, so if we have an instantiation of this class called myObj, then myObj.myProtectedMember won't work, so it is similar in function to a private data member.

Gaulish answered 13/5, 2009 at 20:57 Comment(0)
B
8

I have tried explaining inheritance using a picture below.

The main gist is that the private members of parent class are never directly accessible from derived/child class but you can use parent class's member function to access the private members of parent class. Private variables are always present in derived class but it cannot be accessed by derived class. Its like its their but you cannot see with your own eyes but if you ask someone form the parent class then he can describe it to you. Inheritance Mapping cpp

Boulware answered 22/9, 2020 at 18:29 Comment(0)
C
7

Summary:

  • Private: no one can see it except for within the class
  • Protected: Private + derived classes can see it
  • Public: the world can see it

When inheriting, you can (in some languages) change the protection type of a data member in certain direction, e.g. from protected to public.

Cupro answered 13/5, 2009 at 20:58 Comment(0)
P
7

Private:

The private members of a base class can only be accessed by members of that base class .

Public:

The public members of a base class can be accessed by members of that base class, members of its derived class as well as the members which are outside the base class and derived class.

Protected:

The protected members of a base class can be accessed by members of base class as well as members of its derived class.


In short:

private: base

protected: base + derived

public: base + derived + any other member

Pinkham answered 6/1, 2010 at 14:4 Comment(0)
N
3

It's essentially the access protection of the public and protected members of the base class in the derived class. With public inheritance, the derived class can see public and protected members of the base. With private inheritance, it can't. With protected, the derived class and any classes derived from that can see them.

Nunn answered 13/5, 2009 at 20:51 Comment(0)
I
3

I found an easy answer and so thought of posting it for my future reference too. It's from the link https://www.learncpp.com/cpp-tutorial/115-inheritance-and-access-specifiers/

class Base
{
public:
    int m_nPublic; // can be accessed by anybody
private:
    int m_nPrivate; // can only be accessed by Base member functions (but not derived classes)
protected:
    int m_nProtected; // can be accessed by Base member functions, or derived classes.
};
 
class Derived: public Base
{
public:
    Derived()
    {
        // Derived's access to Base members is not influenced by the type of inheritance used,
        // so the following is always true:
 
        m_nPublic = 1; // allowed: can access public base members from derived class
        m_nPrivate = 2; // not allowed: can not access private base members from derived class
        m_nProtected = 3; // allowed: can access protected base members from derived class
    }
};
 
int main()
{
    Base cBase;
    cBase.m_nPublic = 1; // allowed: can access public members from outside class
    cBase.m_nPrivate = 2; // not allowed: can not access private members from outside class
    cBase.m_nProtected = 3; // not allowed: can not access protected members from outside class
}
Insusceptible answered 24/2, 2015 at 10:5 Comment(0)
E
1

Inheritance

  • public: nothing, same as base class
  • protected: Public -> protected, otherwise same.
  • private (default): Public & protected -> private (everything is now private!)

It's then important to differentiate how a class object looks from the outside vs from the inside.

From inside class: You can access all fields and methods from base that are not private. The kind of inheritance doesn't matter here.

From outside: You can only access methods and fields from class that are public. This means the interface of the base needs to be public and also publicly inherited by derived so that the access propertiers are carried accross.

What about protected?

Protected basically means: Not available from outside, but from inside.

Here's some code to demonstrate it. Everything commented will not compile:

#include <iostream>

struct base {
private:
    int a;
    auto get_a() {return a; }
protected:
    int b;
    auto get_b() {return b; }
public:
    int c;
    auto get_c() {return c; }
};

struct derive_private : private base {
    /* From inside */
    auto print() {
        // a = 3;
        b = 2;
        c = 3;
        // std::cout << get_a() << std::endl;
        std::cout << get_b() << std::endl;
        std::cout << get_c() << std::endl;
    }
};

struct derive_protected : protected base {
    /* From inside */
    auto print() {
        // a = 3;
        b = 14;
        c = 35;
        // std::cout << get_a() << std::endl;
        std::cout << get_b() << std::endl;
        std::cout << get_c() << std::endl;
    }
};

struct derive_public : public base {
    /* From inside */
    auto print() {
        // a = 3;
        b = 14;
        c = 35;
        // std::cout << get_a() << std::endl;
        std::cout << get_b() << std::endl;
        std::cout << get_c() << std::endl;
    }
};

int main() {
    /* From outside */

    derive_private mypriv;
    mypriv.print();
    // mypriv.a = 2;
    // mypriv.b = 5;
    // mypriv.c = 29;
    // std::cout << mypriv.get_a() << std::endl;
    // std::cout << mypriv.get_b() << std::endl;
    // std::cout << mypriv.get_c() << std::endl;

    derive_protected myprot;
    myprot.print();
    // myprot.a = 17;
    // myprot.b = 8;
    // myprot.c = 31;
    // std::cout << myprot.get_a() << std::endl;
    // std::cout << myprot.get_b() << std::endl;
    // std::cout << myprot.get_c() << std::endl;

    derive_public mypub;
    mypub.print();
    // mypub.a = 91;
    // mypub.b = 101;
    mypub.c = 205;
    // std::cout << mypub.get_a() << std::endl;
    // std::cout << mypub.get_b() << std::endl;
    std::cout << mypub.get_c() << std::endl;
}
Epstein answered 28/6, 2023 at 10:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.