0

I am practicing using polymorphism in C++ .

Below is my superclass and subclass implementation.

class Animal{
public:

    int num ;
    string name ;

public:

    Animal()
    {

    };

    Animal( int i, string n)
    {
        num = i;
        name = n ;
    };

    void bark()
    {
        cout<<"---"<<endl;
    };

};

class Cat : public Animal
    {

    public:
        Cat(){  }
        Cat( int i, string n) :  Animal( i, n)
        {
            cout<<"construct "<<"Cat"<<"!!"<<  endl;
        };

        public:

        void bark()
        {
            cout<<"MMM"<<endl;
        }

    };

    class Dog : public Animal
    {
    public:

        Dog() {}
        Dog( int i, string n) :  Animal( i, n)
        {
            cout<<"construct "<<"Dog"<<"!!"<<  endl;
        };

        void bark()
        {
            cout<<"WWW"<<endl;
        }

    };

show(Animal a){
      cout< <a.num << endl << a.name << endl;
        a.bark();
    };

Then , I think if I create a cat and a dog and call show(), the cat will print out MMM and the dog WWW . But after I do this ,

int main()
{

    Cat c1(1,"Kitty") ;
    Dog d1(2,"Doggy");

    cout<<endl;
    show(c1);
    show(d1);

}

The result is ,

construct Cat!!
construct Dog!!

1
Kitty
---
2
Doggy
---

Instead of doing the thing I override in the subclass , the two bark() function still do the thing that super class defined .

But I found that If I use the function directly this way in main() , c1.bark() , it works .

What wrong with this ?

Jeffese
  • 11
  • 2
  • Polymorphism in C++ depends on virtual functions and the use of references or pointers. Your C++ textbook should explain all this. –  Jul 27 '18 at 12:41
  • You need to declare the bark() function as virtual in order to override it. – John Bonda Jul 27 '18 at 12:47
  • I tried to declare it as virtual , virtual void bark() , but the result still the same . – Jeffese Jul 27 '18 at 12:53

0 Answers0