5
votes
 #include <iostream>
using namespace std;

class Base
{
    public:
        Base(){cout <<"Base"<<endl;}
        virtual ~Base(){cout<<"~Base"<<endl;}
        virtual void foo(){ cout<<"foo base"<<endl;}
};

class Derived: private Base
{
    public:
        Derived(){cout<<"Derived"<<endl;}
        virtual ~Derived(){cout<<"~Derived"<<endl;}
        virtual void  foo(){ cout<<"foo dervied"<<endl;}
};


int main(int argc, char *argv[])
{
    Base *pb = new Derived;
    Derived d;
    d.foo();
    return 0;
}

when I execute the above sample program I get following error: protected.cpp: In function ‘int main(int, char**)’: protected.cpp:26: error: ‘Base’ is an inaccessible base of ‘Derived’

Why its not possible to create Derived object with base pointer????


So I can create an instanse of Derived class like

Derived d
Derived d1= new Derived;

But creating instance from Base class pointer like

Base * b = new derived 

will fail.

This is because Derived is not actaully a derived class from Base when derived procted and privately??

Is this correct?????

3
why did this question get 3 downvotes? that is a perfectly legitimate question. +1, ridiculous.mstrobl

3 Answers

6
votes

Why its not possible to create Derived object with base pointer????

Because the base is private. This explicitly forbids treating your class as a Base instance from the outside. Seen from the outside, your class Derived is not a subclass of Base, only from inside the class itself.

The same counts for protected inheritance, with the only difference that the base class now isn't private to the own class any more but rather to any derived class as well. To the outside though, it behaves just like private inheritance.

4
votes

You might want to take a look at this faq on c++ and inheritance. Sections 24.5 and 24.6 in particular.

0
votes

So I can create an instanse of Derived class like

Derived d Derived d1= new Derived; But creating instance from Base class pointer like

Base * b = new derived will fail.

This is because Derived is not actaully a derived class from Base when derived procted and privately??

Is this correct?????

It's exactly like Konrad explained.

It is in reality still derived from Base. To verify this, if you don't override the virtual methods in Derived then the Base versions will get called.

However, since you declared Base as protected the compiler won't let you automatically cast a Derived* to a Base* because the Base superclass is not visible externally.