3

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; } 
1
  • 2
    std::vector<Toy> is a vector of exactly Toys, not of derived types. Read about object slicing, get a good book, and don't assume that things work like in Java.. Commented Apr 26, 2019 at 8:12

1 Answer 1

2

First of all, your printToy function should be virtual. Otherwise no polymorphism can be involved. (Thanks to comment!)

Your vector stores Toys, and only Toys. No polymorphism is involved. In order to use runtime polymorphism, you have to store pointers or the like (unique_ptrs, reference_wrappera, etc.) instead of plain objects. Like this:

std::vector<Toy*> toys; toys.emplace_back(&car); toys.emplace_back(&doll); for (auto& toy : toys) toy->printToy(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Additionally printToy() needs to be a virtual function.
@πάνταῥεῖ Thank you for pointing that out!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.