Search code examples
c++virtual-functionsrvalue-referenceobject-lifetimetemporary-objects

rvalue reference and polymorphism


When I run the following code I get the following runtime crash:

"pure virtual method called terminate called without an active exception"

I dont understand why polymorphism doesn't work here. Please can someone help me.

struct Base
{
    virtual void print()=0;
    virtual ~Base(){}
};

struct Derived: public Base
{
    void print(){cout << "this is Derived\n";}
};

struct Foo
{
    Foo(Base&& r): bref{r} {}
    void print(){
        bref.print();
    }
    Base& bref;
};

int main()
{
    Foo f{Derived()};
    f.print(); //it crashes here with above message
}

Solution

  • The lifetime of the temporary object Derived() extends until the full expression that is Foo f{Derived()};. f.bref is a dangling reference after that. f.print() calls bref.print() which has undefined behaviour.

    Foo{Derived()}.print(); would be technically well defined, but storing an lvalue reference into an rvalue referred object passed to a constructor probably makes no sense.