Difference between private, public, and protected inheritance

user106599 picture user106599 · May 13, 2009 · Viewed 685k times · Source

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

All of the questions I've found on SO deal with specific cases.

Answer

Kirill V. Lyadvinsky picture Kirill V. Lyadvinsky · Sep 3, 2009
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.