Search code examples
c++polymorphismmingwtemporary-objects

C++ - base implementation called through reference of derived?


Consider following code (minimal version):

#include <iostream>

struct Base
{
    virtual ~Base() {}

    virtual void test() const { std::cout << "base"; }
};

struct Derived : public Base
{
    void test() const { std::cout << "derived"; }
};

struct Composite
{
    const Derived &ref;

    Composite(const Derived &ref) : ref(ref) {}

    void testRef() const { ref.test(); }
};

int main()
{
    Composite c((Derived()));
    c.testRef();
}

This actually produces 'base' when using latest MinGW g++! Is that a compiler bug or am I missing something? Could someone test this in VS please?

I consider myself an experienced C++ programmer, constantly using polymorphism, stack-based references, temporary objects (C++ standard 12.2) etc. Therefore I know that lifetime lengthening should be applied.

This behaviour only occurs when defining a destructor in Base (virtual or not) and using a temporary, i. e. following usage produces 'derived':

int main()
{
    Derived d;
    Composite c(d);
    c.testRef();
}

Solution

  • Composite c((Derived()));
    

    This line creates a temporary object of type Derived, passes it to the constructor of c, and then destroys the temporary object. After that, all bets are off.