Problem with inheritance

What is the meaning of this code:

class horse : public vector<animal*>
Last edited on
http://cplusplus.com/doc/tutorial/inheritance/

Also, that particular line is really bad and you probably shouldn't be doing it...
I know inheritance but I don not understand this part vector<animal*>.

(Animal class has been defined.)

This is a part of a program that work fine!
Last edited on
There is no point to this, vector has no virtual members. Just make it a member of Horse itself if you really need access to it from that class.
What you probably want is to create a virtual base class animal and inherit from that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Animal
{
public:
virtual void Eat();
virtual void Move();
//etc.
}

class Horse: public Animal
{
public:
virtual void Eat(); //Here you can implement Horse's specific Eating habits
//etc...
}
In general we use this code:
class horse : public animal

Why this code has changed to:
class horse : public vector<animal*>


It's exactly like the first line. Instead of inheriting from an animal class you are inheriting from a vector<animal*> instead.
Vector is a template class, a container of objects the type of which will be determined at compile time. So you can have a vector containing integers (vector<int>), a vector containing animals (vector<animal>), or, in your case, a vector containing pointers to animals.

So, "vector of pointers to animals" is a real class--the template parameter is defined and there is no more uncertainty about it. The class is totally distinct from, for instance, a vector of integers. And vector<animal*> can be extended by inheritance like any other class you create in C++.

In your case, you defined the class horse to extend (derive from, inherit from, become a subclass of) the class "vector of pointers to animals". (Note: it doesn't make sense, but it is syntactically legal.)
closed account (zb0S216C)
alend wrote:
"I know inheritance but I don not understand this part" vector<animal*>

You're inheriting from the std::vector, and animal* is the type of object the std::vector will hold. However, do not inherit from a std::vector; its destructor is non-virtual.

Wazzak
Last edited on
In your case, you defined the class horse to extend (derive from, inherit from, become a subclass of) the class "vector of pointers to animals". (Note: it doesn't make sense, but it is syntactically legal.)


Many thanks, that makes a sense:).
Topic archived. No new replies allowed.