0

In my java class i remember making a barn class that held animal class objects, and my chicken and cow classes (which were children of the animal class) would fit into the barn as if they were their parents.

i was wondering if c++ also allowed this?

4

2 回答 2

4

Yes it does. The general concept is called the Liskov Substitution Principle.

One issue to be aware of that arises in C++ but not in Java is slicing: What is object slicing?

于 2013-04-12T15:56:02.653 回答
1

In your java example you probably held a reference to a Animal class. In such case you can use any descendant class of Animal class in that reference.

The same is with C++, if you use a pointer to the instance. Like:

class Barn
{
public:
    Animal* animal;
};

class Animal
{
public:
};

class Chicken : public Animal
{
public:
};

The Barn::animal can reference even Chicken class.

I hope this helps.

于 2013-04-12T15:58:19.037 回答