I'm confused about polymorphism in C++. I'm studying it by myself, and I understood its main features. But I don't understand why it is helpful. Before studying polymorphism (about oop), I studied inheritance (that is helpful, because you can use a method in the superclass and subclass writing just only once). Now I'm stuck with polymorphism and the virtual
keyword. I don't understand why it is helpful. See the code below (it's an exercise about C++ institute (I will get a certification)). Why can I declare as "virtual" only functions? I add in the code the variables n1
, n2
, n3
(as public), why cant I access them? I don't understand at all polymorphism, I read tons of posts about polymorphism on StackOverflow, but it's as if I understood polymorphism at 50%. I noticed that polymorphism is less difficult to understand in python because python doesn't have data types, but I want to understand it in C++ also, and its possible uses.
#include <iostream>
using namespace std;
class Pet {
protected:
string Name;
public:
Pet(string n) { Name = n; }
virtual void MakeSound(void) { cout << Name << " the Pet says: Shh! Shh!" << endl; }
int n1;
};
class Cat : public Pet {
public:
Cat(string n) : Pet(n) { }
void MakeSound(void) { cout << Name << " the Cat says: Meow! Meow!" << endl; }
int n2;
};
class Dog : public Pet {
public:
Dog(string n) : Pet(n) { }
void MakeSound(void) { cout << Name << " the Dog says: Woof! Woof!" << endl; }
int n3;
};
int main(void) {
Pet* a_pet1, * a_pet2;
Cat* a_cat;
Dog* a_dog;
a_pet1 = a_cat = new Cat("Kitty");
a_pet2 = a_dog = new Dog("Doggie");
a_pet1->MakeSound();
a_cat->MakeSound();
static_cast<Pet*>(a_cat)->MakeSound();
a_pet2->MakeSound();
a_dog->MakeSound();
static_cast<Pet*>(a_dog)->MakeSound();
}