Hello. I am having a problem with a program. I have a bunch of classes all derived from the same base class. I want to loop through a vector of objects, calling a function in each. The problem is that it doesn't matter which class the objects are, only the function defined in the base class is called.
I simplified the code as far as possible to replicate the problem. As you see, I would like a mix of numbers 1,2,3 as the output, however using the vector the only number output is 1. Here is a copy of the output by the way:
base->num() : 1
a->num() : 2
b->num() : 3
(*it)->num() : 1
(*it)->num() : 1
(*it)->num() : 1
I suspect this is the "slice" problem, because the vector is defined with pointers to the base class so it uses the base class functions? The question is how to get around it? How can I loop through a vector of objects sharing the same base class but calling each by their correct member functions?
I am thankful for any help.
Code:#include <iostream> #include <vector> class Base { public: int num() { return 1;} }; class HeirA : public Base { public: int num() { return 2;} }; class HeirB : public Base { public: int num() { return 3;} }; int main(int argc, char** argv) { Base* base = new Base(); HeirA* a = new HeirA(); HeirB* b = new HeirB(); // Explicitly specifying each object. std::cout << "base->num() : " << base->num() << std::endl; std::cout << "a->num() : " << a->num() << std::endl; std::cout << "b->num() : " << b->num() << std::endl; // Looping through a vector. std::vector<Base*> list; list.push_back(base); list.push_back(a); list.push_back(b); std::vector<Base*>::iterator it = list.begin(); while (it != list.end()) { std::cout << "(*it)->num() : " << (*it)->num() << std::endl; ++it; } }