문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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.

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

If you want polymorphism, do this:

class Parent {
public:
    virtual someFunc() { /* implementation A */ };
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top