Difference between private, public, and protected inheritance

后端 未结 16 1807
灰色年华
灰色年华 2020-11-21 06:15

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

16条回答
  •  一整个雨季
    2020-11-21 06:34

    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.

提交回复
热议问题