开发者

Upcasting instance and Invoking a function on base class in C++

class PureVirtual
开发者_运维技巧{
public: virtual PureVirtual& Foo () = 0;
        virtual ~PureVirtual () {}
};

class SemiVirtual : public PureVirtual
{
public: PureVirtual& Foo () { printf ("foo worked."); return *this; }
        virtual ~SemiVirtual () {}
};

class NonVirtual : public SemiVirtual
{
public: NonVirtual& Bar () { printf ("bar worked."); return *this; }
};

TEST (Virtualism, Tests)
{
    PureVirtual& pv = NonVirtual ().Bar().Foo (); <-- Works
    pv.Foo (); // <- Crashes
}

pv.Foo crashes because pv instance has been disposed. How can i prevent this situation, and invoke the foo function without using pointers but by reference?


Because you initialized pv with reference to temporary object. "Temporary object" will be automatically destroyed in the next line, after that all calls to non-static methods that use class members, and all virtual methods will crash the application.

Use pointers. Or this:

TEST (Virtualism, Tests)
{
    NonVirtual v;
    PureVirtual& pv = v.Bar().Foo(); <-- Works
    pv.Foo ();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜