pointer to derived class query

Hey All, I'm quite new to C++ and I have a query regarding pointers and derived class objects
say I have the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class animal
{
private:
string name;
};

class dog:animal
{
private:
int legs;
public:
void display()
{
cout<<legs;
}
};


Would I be able to say something like this:
1
2
3
animal *a[10];
a[0]=new dog();//is this a valid statement?
a[0]->display()//Can I access the display function of the derived class? 


If the answer to both the questions is a "No", then what's the way to go about it?


line 2 is valid, line 3 is not. animal needs a (pure) virtual display() function.

however you have more problems. Since name is private in animal, dog cannot access it. You need to
make name protected.

you are inheriting animal privately in dog. you should be inheriting it publicly.
Hi. These statements would be legal if:
1. you declare virtual function display() in animal
2. you use public inheritance between animal and dog

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class animal
{
private:
	string name;
public:
	virtual void display() = 0;
};

class dog: public animal
{
private:
	int legs;
public:
	void display() { cout << legs; }
};
Thanks for your replies guys. It really helped me. I'm just trying to create a heterogeneous list and I guess this approach should do it.
Topic archived. No new replies allowed.