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 ?