Reputation: 529
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
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
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:
public
inheritanceDog*
to
Animal*
is not neededUpvotes: 3
Reputation: 32490
To correct your compiler error simply do:
Animal* pDog2 = reinterpret_cast<Animal*>(new Dog());
Upvotes: 1