When I make an Animal
pointer to hold a Duck
object and use a method make_choice
that returns an enum
, it looks as though the method belonging to the base Animal
class is being used instead of the derived Duck
class. How do I instead retain use of the derived classes method?
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
enum Choice{None, Egg, Bone};
class Animal {
protected:
std::string noise = "None";
public:
Animal() = default;
virtual ~Animal() = default;
virtual std::string getNoise() {
return noise;
}
virtual Choice make_choice(){
return None;
}
};
class Duck : public Animal {
public:
Duck() {
noise = "Quack!";
}
Choice make_choice() override {
return Egg;
}
};
int main() {
Duck duck;
cout << duck.make_choice() << endl; // should be 1 for Egg
std::shared_ptr<Animal> duckPtr = std::make_shared<Animal>(duck);
cout << duckPtr->make_choice() << endl; // also should be 1 for Egg, but is 0 for None
return 0;
};
Output:
1 // for Egg
0 // for None