Suppose I have a class with a virtual function and a derived class that implements the virtual function in a different way. Suppose I also have a vector of the base class used to store derived classes. How would I execute the virtual function of a derived class in the vector without knowing in advance what the derived class is? Minimal code that illustrates the problem:
#include <iostream>
#include <vector>
class Foo {
public:
virtual void do_stuff (void) {
std::cout << "Foo\n";
}
};
class Bar: public Foo {
public:
void do_stuff (void) {
std::cout << "Bar\n";
}
};
int main (void) {
std::vector <Foo> foo_vector;
Bar bar;
foo_vector.resize (1);
foo_vector [0] = bar;
bar.do_stuff (); /* prints Bar */
foo_vector [0].do_stuff (); /* prints Foo; should print Bar */
return 0;
}
std::vector<Foo*>
(by pointer, or by reference), to avoid object slicing? Otherwise, the moment you assignbar
object to the vector, it has been sliced (a newFoo
is created and stored in the vector, instead of yourbar
), which is probably not what you want. Using pointer will make code more complicated, though. – Erkan