UnknownError1337
UnknownError1337

Reputation: 1222

C++ inheritance, how solve this?

How can I solve this? I want to execute proper method something. Is there any way to solve this? I want to execute method something in one loop.

class Base
{
public:
    void something() {}
};

class Child : public Base
{
public:
    void something() {}
};

class SecondChild : public Base
{
public:
    void something() {}
};

std::vector<Base*> vbase;

Child * tmp = new Child();

vbase.push_back((Base*) tmp);

SecondChild * tmp2 = new SecondChild();

vbase.push_back((Base*) tmp);

for (std::vector<Base*>::iterator it = vbase.begin(); it != vbase.end(); it++)
{
    //here's problem, I want to execute proper method "something", but only I can do is execute Base::something;
    (*it)->something();
}

I don't know how to cast type, when I got many children of base class.

Upvotes: 1

Views: 108

Answers (3)

Eric Finn
Eric Finn

Reputation: 9005

The solution is to make something() a virtual function.

class Base {
public:
    virtual void something() {}
};
...
[in a function]
Base *p = new Child;
p->something(); //calls Child's something

Upvotes: 3

Johan Lundberg
Johan Lundberg

Reputation: 27028

You need to declare the method as virtual in the base class.

Upvotes: 4

Rapptz
Rapptz

Reputation: 21317

A couple of things.

One, you don't need to cast stuff to (Base*). Implicit conversions will do that for you already. Second, if you define your functions as virtual it will call the proper function for you.

Upvotes: 10

Related Questions