Reputation: 69988
struct B {}; // B contains data members
struct D : B {}; // D doesn't contain ANY data member
B g_b; // global object
D& fun () // want to return by reference ONLY
{
return <???>(g_b); // how ???
}
[Note: I want to avoid overloading constructor (or assignment) such as D(const B&)
.]
Upvotes: 2
Views: 109
Reputation: 361342
No suitable cast. That is in fact undefined behavior.
For detail, see this topic: Downcasting a base type
Note : the term is downcast when you cast base to derived class; and the term upcast is used when you cast derived to base class.
Upvotes: 2
Reputation: 206518
That is undefined behavior.
You can use dynamic_cast
for performing safe down casting of Base class pointer/reference to derived class pointer/reference. It returns a null in case of pointers or throws an exception in case of references.
Upvotes: 1