2

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;
}
Tom
  • 81
  • 1
  • 6
  • 2
    `std::vector` is a vector of *exactly* `Toy`s, not of derived types. Read about [object slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing), get [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), and don't assume that things work like in Java.. – molbdnilo Apr 26 '19 at 08:12

1 Answers1

1

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();
L. F.
  • 19,445
  • 8
  • 48
  • 82