Downcasting with private inheritance

Dec 8, 2009 at 7:51pm
Can anybody tell me what is the prob here?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

class Animal
{
public:
	virtual void speak()
	{
		cout << "Animal speaks" << endl;
	}
};

class Dog : private Animal
{
public:
	virtual void speak()
	{
		cout << "Dog barks" << endl;
	}
};

void main()
{
	Animal* pA = new Animal;
	Dog* pD = new Dog;

	pA = pD;

	pA->speak();
}


The error is:
error C2243: 'type cast' : conversion from 'Dog *' to 'Animal *' exists, but is inaccessible
Dec 8, 2009 at 7:54pm
To do what you are trying to do, you need public inheritance or the pointers will be incompatible
Dec 8, 2009 at 8:30pm
Bazzy, I know public inheritance will work. I read somewhere that private inheritance is preferred over composition, when virtual functions in the base class needs to be overriden in derived classes, and that's what I am doing here. Well, can you tell me how could I implement the statement above in bold? Thanks.
Dec 8, 2009 at 8:49pm
You want polymorphism, private inheritance has different purposes:
http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.2
Topic archived. No new replies allowed.