Reputation: 508
I am trying to achieve Polymorphism whereby a specific method of the derived class is called based on the instance passed to the function.
I'm not sure if this is possible. Any guidance would be much appericated.
This is the code:
#include <iostream>
using namespace std;
class Animal
{
public:
void speak()
{
cout << "Base: Animal Speaking!" << endl;
}
};
class Dog : public Animal
{
public:
void speak()
{
cout << "Dog: Woof!" << endl;
}
};
class Cat : public Animal
{
public:
void speak()
{
cout << "Cat: Meow!" << endl;
}
};
class FarmAnimal : public Animal
{
public:
void speak(Animal *animal)
{
animal->speak();
}
};
int main()
{
Dog dog = Dog();
Cat cat = Cat();
FarmAnimal farm_animal = FarmAnimal();
dog.speak();
cat.speak();
farm_animal.speak(&dog);
farm_animal.speak(&cat);
return 0;
}
Output:
Dog: Woof!
Base: Meow!
Base: Animal Speaking!
Base: Animal Speaking!
Expected Output:
Dog: Woof!
Base: Meow!
Dog: Woof!
Cat: Meow!
Upvotes: 0
Views: 134
Reputation: 6131
Sure you can.
I recommend making Animal an "abstract" base class. Declare the functions virtual
and make them "pure" by setting them to 0 (forcing derived classes to override them to be able to be instantiated.)
class Animal
{
public:
virtual ~Animal() = default; // allows polymorphic destruction too
virtual void speak() = 0;
};
Then mark you derived classes as overriding the base:
class Dog : public Animal
{
public:
void speak() override
{
cout << "Dog: Woof!" << endl;
}
};
class Cat : public Animal
{
public:
void speak() override
{
cout << "Cat: Meow!" << endl;
}
};
As for FarmAnimal
, I wouldn't go crazy on inheritance. This class looks like a strange model, as it operates on other animals, not itself. Overdoing inheritance leads to convoluted designs.
Upvotes: 3