How to register a derived class member function pointer with a base class

大城市里の小女人 提交于 2019-12-03 03:13:28

If all you need is beating the error message, then casting will do:

class Derived : public Base
{
    Derived() {
        registerPrepFn( static_cast<PrepFn>(&Derived::derivedPrepFn) );
    };

    void derivedPrepFn( int n ) {};

}

Call it normally with a Base* p (provided it actually points to a Derived): (p->*registered)(0)

See http://ideone.com/BB9oy for a working example.

This is not allowed with oop. Behavioural switching is accomplished by polymorphing the object's class at object creation time.

If you need post-object-creation behaviour switching, you might refactor the dynamic behaviour to another set of polymorphic classes and hold a "pointer" to an instance of a class with the correct behaviour. Please Google the "decorated class" software pattern.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!