Preface: I want to be able to store a (abstract) base class reference from an object of a derived (concrete) class type so it can be returned later and casted to the same derived (concrete) class without resorting to pointers and constantly having to worry about ownership, memory leaks, and dangling pointers/bad references.
Using the hierarchy below, the attempted constructor call: A(/* Other variables */, Bar(/* Bar variables */)); fails with `Warning 3 warning C4239: nonstandard extension used : ‘argument’ : conversion from ‘Bar’ to ‘Foo&’ (Visual Studio 2010 SP1)
Changing the class O to contain a Foo* _foo and the constructor initialization to /*...*/, _foo(&foo) causes a dangling pointer as the temporary object is destroyed when the constructor finishes.
Is there a way to pass a temporary object to a class that expects a reference and not have the code go bonkers?
`
/* ABSTRACT BASE CLASS */
class Foo {
//...
};
/* DERIVED, CONCRETE CLASS */
class Bar : public Foo {
//...
};
class O {
O(/* Other variables */, Foo& foo) : /* Other member variable initializations */, _foo(foo) { }
//...Other member variables here...
Foo& _foo;
friend class A;
};
class A {
public:
A(/* Other individual variables used to fully construct object 'O' */, Foo& foo) : /*...*/, _foo(foo) { }
private:
O _o
};
No. The very reason why you do not have to worry that much about ownership when you deal with references is that the ownership is dealt with some place else – specifically, at the level owning the variable being referenced.
A reference becomes invalid the moment the object being referenced goes out of scope (yes, references can be dangling too). The object being referenced must stay around as long as the reference to it is in active use. That is why you cannot make temporaries play nicely with references: temporaries go out of scope very quickly, rendering useless the references to them.