开发者

Call virtual method from base class on object of derived type

开发者 https://www.devze.com 2022-12-29 18:17 出处:网络
class Base { public: virtual void foo() const { std::cout << \"Base\"; } }; class Derived开发者_开发知识库 : public Base
class Base
{
public:
    virtual void foo() const
    {
        std::cout << "Base";
    }
};

class Derived开发者_开发知识库 : public Base
{
public:
    virtual void foo() const
    {
        std::cout << "Derived";
    }
};

Derived d; // call Base::foo on this object

Tried casting and function pointers but I couldn't do it. Is it possible to defeat virtual mechanism (only wondering if it's possible)?


To explicitly call the function foo() defined in Base, use:

d.Base::foo();


d.Base::foo();

Note that d.foo() would call Derived::foo regardless of whether foo was virtual or not.

0

精彩评论

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