Is there a way to call a base function outside of

2020-07-02 11:22发布

This question is similar, but is about calling the function from inside the class: Can I call a base class's virtual function if I'm overriding it?

In that case, you'd specify Base::function() instead of function(), which will call the overridden definition.

But is there a way to do this outside of the class? My class doesn't define a copy constructor, so I couldn't figure out how to cast as the base class:

Base( derived_object ).function()

Is the appropriate thing to do here to cast & derived_object as Base* and then call ->function()?

Thanks for your insight.

标签: c++ oop
3条回答
手持菜刀,她持情操
2楼-- · 2020-07-02 11:54

I believe the syntax:

derived_ptr->Base::function();

works just fine. Though I really question why you would want to do this in a function that's not part of your class. Especially if function happens to be a virtual function.

The reason why it's a questionable idea is that you're making whatever it is that uses that notation depend on the inheritance hierarchy of your class. Also, functions are usually overridden for a reason. And you're getting around that by using this syntax.

查看更多
干净又极端
3楼-- · 2020-07-02 12:02

Try derived_object.Base::function();

查看更多
Viruses.
4楼-- · 2020-07-02 12:15

You probably want to use pointers to member functions of a class. Those give you the ability to map different base class functions to the pointer as needed, and the ability to use it as a variable or function parameter.

The syntax for a pointer to a member function looks like

class Base
{
public:
    virtual bool Function();
    virtual bool OtherFunction();
};

typedef bool (Base::*)() BaseFunc;

The list of caveats for using these things is a mile long- there is plenty online on how to use them (most of the answers are "don't"). However, they do give you a way of clearly binding to and calling a base class member function.

查看更多
登录 后发表回答