We want to allow our pets to communicate, so let's add a public member function to the Pet class called speak(). This should be implemented polymorphically so that when you ask a Cat instance to speak(), it will write "Meow" to stdout, and if you ask a Dog to speak(), it will write "Woof" to stdout.
What should this look like and what would be a good way to understand Polymorphically?
The example problem I'm working through is fairly straight forward and I've gotten to the above instruction, I was hoping to find some guidance. Thank you.
class Pet
{
public:
std::string petName;
Pet();
Pet(std::string petName,);
~Pet();
void speak();
};
class Dog : public Pet
{
};
class Cat : public Pet
{
};
In polymorphism, both of the classes that extends the superclass (Dog and Cat) must implement differently the methods that are performed differently by each of them. So, when you extend a superclass that has the void speak() method in it, if you want them to perform differently the speak method, you should implement it again on both subclasses; Something like that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Dog : public Pet {
void speak(){
cout << "bark" << endl;
}
};
class Cat : public Pet {
void speak(){
cout << "meow" << endl;
}
};
// Example program
#include <iostream>
#include <string>
class Pet
{
public:
virtual ~Pet() { }
virtualvoid speak();
};
void Pet::speak()
{
std::cout << "Generic pet sound!\n";
}
class Dog : public Pet
{
public:
void speak() override;
};
void Dog::speak()
{
std::cout << "Woof!\n";
}
class Cat : public Pet
{
public:
void speak() override;
};
void Cat::speak()
{
std::cout << "Meow!\n";
}
void func(Pet& pet) // passed by REFERENCE
{
pet.speak();
}
int main()
{
//
// Polymorphism can be invoked through a pointer:
//
Pet* pet = new Pet;
Dog* dog = new Dog;
Cat* cat = new Cat;
pet->speak();
dog->speak();
cat->speak();
delete pet;
delete dog;
delete cat;
//
// or through references:
//
Pet pet2;
Dog dog2;
Cat cat2;
Pet& pet2_ref = pet2;
Dog& dog2_ref = dog2;
Cat& cat2_ref = cat2;
pet2_ref.speak();
dog2_ref.speak();
cat2_ref.speak();
//
// Even more useful when passing to a function:
//
func(dog2);
}
Generic pet sound!
Woof!
Meow!
Generic pet sound!
Woof!
Meow!
Woof!
The usefulness of this shows itself when passing a polymorphic object to a function.
You can pass a dog object to something expecting a Pet reference, and the behavior will differ based on what the subclass of the reference is. See the "func" function.