views:

40

answers:

3

Consider the following simple polymorphism ...

class Parent {
public:
    someFunc() { /* implementation A */ };
};

class Child : public Parent {
public:
    someFunc() { /* implementation B */ };
};

int main ()
{
    Parent* ptr;

    ptr = new Parent();
    ptr->someFunc();
    delete ptr;

    ptr = new Child();
    ptr->someFunc();
    delete ptr;

    return 0;
}

As far as I can tell, in both cases implementation A will be called.

How can I call the "most derived" implementation of someFunc, depending on the dynamic type of ptr?

In my real code there are many children types, so it wouldn't be practical to use dynamic_cast to check per child class.

+3  A: 

Declare someFunc virtual. This will ensure that the implementation of the actual object is called, not the implementation depending on the pointer type.

This will, however, add some overhead connected with the creation of the VTABLE and slower calling of the virtual function, but is essentially what polymorphism is.

Michał Trybus
+4  A: 

Try:

class Parent 
{
    public:
         virtual someFunc() { /* implementation A */ };
       //^^^^^^^
};

Though technically not required.
I always find it good style to also declare the derived function virtual:

class Child : public Parent 
{
    public:
        virtual someFunc() { /* implementation B */ };
};

Unlike Java functions are not virtual by default.

Martin York
+2  A: 

There is no polymorphism here! None of your functions are virtual.

If you want polymorphism, do this:

class Parent {
public:
    virtual someFunc() { /* implementation A */ };
};
John Dibling