Dinesh Khandelwal
Dinesh Khandelwal

Reputation: 327

Instantiating Derived class which inherits privately or protectedly from Base

I have the following hypothetical code:

class Base {
public:
    virtual void print() {
        std::cout << "Base\n";
    }
    // assume virtual destructor
};

class Derived : private Base {
public:
    void print() {
        std::cout << "Derived\n";
    }
};

int main() {
    // Derived d{};   works fine
    Base *pd = new Derived{}; // doesn't work
    pd->print();
    // assume memory is deallocated  
}

At first, I thought that it would work, because constructors aren't inherited anyways. But the compiler gives the error:

error: 'Base' is an inaccessible base of 'Derived'

And I'm not able to figure out what is really happening?

Upvotes: 2

Views: 85

Answers (3)

Dominique McDonnell
Dominique McDonnell

Reputation: 2520

In a context where the knowledge of the internals of the derived class is hidden (IE non-friend, not in a class derived from Derived) it seems like there is no relationship between the two classes.

When you try to assign to a pointer of the base type you are saying convert this Derived pointer to a Base pointer. As the inheritance is hidden, it is like you are trying to assign it to a pointer of an unrelated type. However the compiler does know that it is related, so rather than just giving you a unhelpful error, it tells you that the conversion that you are trying to do is inaccessible.

Upvotes: 0

R2-Dequeue
R2-Dequeue

Reputation: 638

It's a good guess, but the problem isn't with constructors or member functions.

In the line

Base *pd = new Derived{}; // doesn't work

The compiler is implicitly converting the right side, new Derived{}, which is of type Derived*, to the type Base*.

The term that the standard uses to describe when one can implicitly convert a pointer to a derived class to a pointer to a base class is accessibility. From subsection 11.2/5:

If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class

There are a few technical conditions listed (11.2/4 if you really care) that can make a base class accessible, but Base meets none of these.

The short version is, private inheritance hides the base class and the access specifier private needs to be public for your code to compile. Hope that helps.

Upvotes: 4

Nishant
Nishant

Reputation: 1665

You are deriving Base privately, and that's why you are getting error.

With private inheritance, all members from the base class are inherited as private. This means private members stay private, and protected and public members become private. Thats why you are not able to use print()in main Compiler is not able to cast derived pointer to base type, because the inheritance is private.

Upvotes: 1

Related Questions