tags:

views:

51

answers:

2
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?

+1  A: 

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 ();
}
SigTerm
You can bind a temporary to a const reference to extend its lifetime.
Martin York
jack london
A: 

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

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

See this Herb Sutter's article for details http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/