0

I'm trying a bit with polymorphism with the following code snippet:

#include <iostream>
#include <vector>

using namespace std;

struct Foo {
    virtual void f() {
        cout << "f from Foo" << endl;
    }
};

struct Bar : public Foo {
    void f() {
        cout << "f from Bar" << endl;
    }
};

int main() {
    Foo foo;
    Bar bar;
    vector<Foo> fooV;
    fooV.push_back(foo);
    fooV.push_back(bar);
    for(auto it = fooV.begin(); it != fooV.end(); ++it)
        it->f();
}

I expected that since f() is overridden, one of them would print "f from Foo" and the other "f from Bar". However, the output of the program is

f from Foo
f from Foo

I should also note that I also tried adding the keyword override to the declaration of f() in Bar, since I'm using C++11. It didn't have any effect.

limp_chimp
  • 13,475
  • 17
  • 66
  • 105

4 Answers4

4

Try this

int main()
{
    Foo foo;
    Bar bar;
    vector<Foo*> fooV;
    fooV.push_back(&foo);
    fooV.push_back(&bar);
    for (auto it = fooV.begin(); it != fooV.end(); ++it)
        (*it)->f();
}

To achieve polymorphism advantages you should use pointers or references to derived objects.

masoud
  • 55,379
  • 16
  • 141
  • 208
1

This

fooV.push_back(bar);

copies Foo part of bar only - a struct Foo object ends up inside vector. Since the new object is of type struct Foo it's no wonder Foo::f() is being called later.

You can only store objects of one distinct type in vector so for your case you'll have to store pointers to objects instead of objects themselves.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
0

You have a vector of Foo. Adding a Bar to that vector simply copies the Foo part of that Bar in to the vector (ignoring the other data).

Mankarse
  • 39,818
  • 11
  • 97
  • 141
0
vector<Foo> fooV;

As you are creating the vector of Foo then the function of Foo will only be called not of Bar

Saurabh B
  • 165
  • 10