Search code examples
c++access-specifier

c++ derived class with private access specifier


I have a derived class (class B) from a base class (class A). Class A has a protected virtual function foo() which I want to override and use it as private in derived class.

Class A{
  protected:
   virtual void foo() = 0;
}

I am wondering whether the following

Class B: public Class A
  private:
    virtual void foo();

and

Class B: private Class A
  private:
    virtual void foo();

are the same.


Solution

  • They are not the same. In the first example, B is-an-A, in the second it isn't. So in the first case you can have code such as

    void foo(const A& a);
    

    which accepts A and B as arguments. With private inheritance, you could not do that. For example,

    A a;
    B b;
    foo(a); // OK with private and public inheritance
    foo(b); // OK only with public inheritance, i.e. B is an A.