Having some trouble with c++ and polymorphism. I realise this is a very simple question but I'm really struggling with the move from java to c++ particularly regarding pointers.
I have a 'Toy' class, and inheriting from that I have 'Doll' and 'Car' classes. In each class I have a function called printToy(); I have a vector which holds Doll, Toy and Car objects. I want to iterate through the vector calling 'printToy()' at each index however when I do this it calls the method from Toy class thus giving me an output of 'Toy Toy Toy' instead of 'Toy Doll Car'. Thanks to anyone who can help me!
Here is the example:
class Toy{
public:
void printToy(){
std::cout<<"Toy"<<std::endl;
}
};
class Doll: public Toy{
public:
void printToy(){
std::cout << "Doll" << std::endl;
}
};
class Car: public Toy{
public:
void printToy(){
std::cout << "Car" << std::endl;
}
};
int main(){
std::vector<Toy> toys;
Toy toy;
Doll doll;
Car car;
toys.push_back(toy);
toys.push_back(doll);
toys.push_back(car);
for(int i = 0; i < toys.size(); i++){
toys[i].printToy();
}
return 0;
}