sivic
sivic

Reputation: 529

Private inheritence and constructors

I have following problem:

Here is an example (compile error):

class Animal
{
public:
    explicit Animal(void){;}
};

class Dog: private Animal
{
public:
    explicit Dog(void){;}
};

int main(int argc, char *argv[])
{
    Dog* pDog1 = new Dog();

    Animal* pDog2 = new Dog();

    return 0;
}

How can I solve this? Thanks!

edit: Let's say that Base class is inherited from some library thus i cant change it.

Upvotes: 1

Views: 203

Answers (3)

Jem
Jem

Reputation: 2275

As an alternative to reinterpret_cast, you may expose the base class with a method. If one day you decide to use composition instead of inheritance, it won't break your code:

class Dog: private Animal
{
public:
    explicit Dog() {}
    Animal * GetAnimal() { return this; }
};

int main(int argc, char *argv[])
{
    Dog* pDog1 = new Dog();
    Animal * pDog2 = pDog1->GetAnimal();
    return 0;
}

Upvotes: 3

iammilind
iammilind

Reputation: 69988

want to inherit some class as protected

Then theoretically it should be, class Dog : protected Animal.

Now, for any non-public inhertiance, Base *p = new Derived; is invalid; as Base* becomes inaccessible. Without reinterpret_cast<> or C-style cast it cannot be done.

I will suggest not to use casts. Ideally, for private/protected inheritance, base pointer is not supposed to hold derived pointer in general scope. To solve your problem:

  1. Either make the public inheritance
  2. Change design where the cast from Dog* to Animal* is not needed

Upvotes: 3

Jason
Jason

Reputation: 32490

To correct your compiler error simply do:

Animal* pDog2 = reinterpret_cast<Animal*>(new Dog());

Upvotes: 1

Related Questions