Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private inheritance

I dont completely understand this:

class Base
{
    public:
    Base()
    {
        cout<<"Base" << endl;
    }

    virtual void call()
    {
        cout<<"Base call" << endl; 
    }
};

class Derived: private Base
{
    public:      
    Derived()
    {
        cout<<"Derived" << endl;
    } 
};

int main(void)
{
    Base *bPtr = new Derived(); // This is not allowed
}

Is it because someone might call call() using bPtr which is actually done on derived object? Or is there any other reason?

like image 577
nitin soman Avatar asked Oct 16 '09 09:10

nitin soman


People also ask

What is the difference between private and protected inheritance?

protected inheritance makes the public and protected members of the base class protected in the derived class. private inheritance makes the public and protected members of the base class private in the derived class.

Can private members be inherited?

Private Members in a SuperclassA subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

How can you make the private members inheritance?

The private members of a class can be inherited but cannot be accessed directly by its derived classes. They can be accessed using public or protected methods of the base class. The inheritance mode specifies how the protected and public data members are accessible by the derived classes.

What is purpose of private inheritance in C++?

The private -inheritance variant allows access to the protected members of the base class. The private -inheritance variant allows Car to override Engine 's virtual functions.


1 Answers

Public inheritance means that everyone knows that Derived is derived from Base.

Protected inheritance means that only Derived, friends of Derived, and classes derived from Derived know that Derived is derived from Base.*

Private inheritance means that only Derived and friends of Derived know that Derived is derived from Base.

Since you have used private inheritance, your main() function has no clue about the derivation from base, hence can't assign the pointer.

Private inheritance is usually used to fulfill the "is-implemented-in-terms-of" relationship. One example might be that Base exposes a virtual function that you need to override -- and thus must be inherited from -- but you don't want clients to know that you have that inheritance relationship.

*also: how much wood would a woodchuck chuck...

like image 106
Kaz Dragon Avatar answered Oct 08 '22 00:10

Kaz Dragon