qwarten
qwarten

Reputation: 105

Executing an overwritten inherited function

Say I have these two classes:

class Object {
public:
    virtual void update();      
};

class Actor : public Object {
public:
    void update();
}

Also assume that I am creating instances of the actor class as follows:

class somethingElse {
public:
    void init();

    std::vector<Object*> objects;
}

void somethingElse::init()
{
    Actor tmp;
    Object * tmpo = &tmp;
    objects.push_back(tmpo);
}

I later iterate through objects:

for (int i = 0; i < objects.size(); i++)
    objects.at(i)->update();

Placing a breakpoint at the two versions of update() revealed that the one being called is the one from the object class, and not the one from the actor class. Why is this, and is there any way around this problem?

Upvotes: 0

Views: 46

Answers (1)

wally
wally

Reputation: 11022

In somethingElse::init() Actor tmp will go out of scope and be destroyed. The pointer will point to an object that no longer exists.

new could help here, but it would be safer to use a smart pointer, such as std::shared_ptr for example:

#include <iostream>
#include <vector>
#include <memory>

class Object {
public:
    virtual void update() { std::cout << "Object update()\n"; }
    virtual ~Object() = default;
};

class Actor : public Object {
public:
    void update()  { std::cout << "Actor update()\n"; }
};

class somethingElse {
public:
    void init();

    std::vector<std::shared_ptr<Object>> objects;
};

void somethingElse::init()
{
    //Actor tmp;
    auto tmpo = std::make_shared<Actor>();
    //Object * tmpo = &tmp;
    objects.push_back(tmpo);
}

int main()
{
    somethingElse objs;
    objs.init();
    auto& objects = objs.objects;


    for(int i = 0; i < objects.size(); i++)
        objects.at(i)->update();
}

Upvotes: 2

Related Questions