开发者

How to call child object's overloading function in polymorphism?

开发者 https://www.devze.com 2023-01-19 18:06 出处:网络
Consider the following simple polymorphism ... class Parent { public: someFunc() { /* implementation A */ };

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 */ };
};
0

精彩评论

暂无评论...
验证码 换一张
取 消