Instance instance and function call in 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 failed because the pv instance was deleted. How can I prevent this situation and call the foo function without using pointers, but by reference?

+3
source share
2 answers

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

Use pointers. Or that:

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

Use the const link if you can. This extends the lifetime of the temporary variable.

const PureVirtual& pv = NonVirtual().Bar().Foo();

http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

0

Source: https://habr.com/ru/post/1758273/


All Articles