iammilind
iammilind

Reputation: 69988

What is the most suitable way to return base object to up-casted derived class?

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

Answers (3)

Mat
Mat

Reputation: 206689

What you're trying to do is illegal. g_b is not a D.

Upvotes: 5

Sarfaraz Nawaz
Sarfaraz Nawaz

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

Alok Save
Alok Save

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

Related Questions