Vector of pointers to base class, odd behaviour calling virtual functions

Posted by Ink-Jet on Stack Overflow See other posts from Stack Overflow or by Ink-Jet
Published on 2010-05-13T21:55:54Z Indexed on 2010/05/13 22:04 UTC
Read the original article Hit count: 423

Filed under:
|
|

I have the following code

#include <iostream>
#include <vector>

class Entity {
public:
    virtual void func() = 0;
};

class Monster : public Entity {
public:
    void func();
};

void Monster::func() {
std::cout << "I AM A MONSTER" << std::endl;
} 

class Buddha : public Entity {
public:
    void func();
};

void Buddha::func() {
std::cout << "OHMM" << std::endl;
}

int main() {
const int num = 5;  // How many of each to make
std::vector<Entity*> t;

for(int i = 0; i < num; i++) {
    Monster m;
    Entity * e;
    e = &m;

    t.push_back(e);
}

for(int i = 0; i < num; i++) {
    Buddha b;   
    Entity * e;
    e = &b;

    t.push_back(e);
}

for(int i = 0; i < t.size(); i++) {
    t[i]->func();
}

return 0;
}

However, when I run it, instead of each class printing out its own message, they all print the "Buddha" message. I want each object to print its own message: Monsters print the monster message, Buddhas print the Buddha message.

What have I done wrong?

© Stack Overflow or respective owner

Related posts about c++

Related posts about inheritance