Question

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.

Was it helpful?

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.

OTHER TIPS

No, your two cases are not the same.

In the second case class B can't be casted to class A, because a private base class is hidden. in this aspect would get the same behavior as if class A would be a member of class B.

No both are not same In public inheritance class A's foo() will be protected member in class B In private inheritance class B can only access the public members of the class A so there will not present any foo() of class A in class B.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top