C ++: calling a virtual function of a derived class

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 base class vector used to store derived classes. How to perform a virtual function of a derived class in a vector without knowing in advance what a 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;
}
+5
source share
3 answers

You can not. Objects in the vector will be sliced ​​- any data from an instance of the derived class will be chopped off, so calling a method would be a very bad idea.

, , , .

+14

, , Bar, Foo. , foo_vector [0] = bar;, - =, , - . - Foo, .

+2

. , ( " , , ?" , , " " ).

Using marking a function as virtual is what you ask the compiler to defer or determine the "TYPE" of the object that calls this function at run time, rather than the usual "compile time" method. This is achieved using pointers to objects. Therefore, to put it in a simple line "Use pointers to objects to use virtual functions."

0
source

All Articles