2
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&).]

iammilind
  • 68,093
  • 33
  • 169
  • 336

3 Answers3

5

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

Mat
  • 202,337
  • 40
  • 393
  • 406
  • `g_b` you mean, but yes. It's an instance of `B` only, not `D`. There's no legal way to refer to it via a `D&`, because `D&` means "reference to an instance of D". Which it isn't :-) – Steve Jessop May 17 '11 at 17:21
2

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.

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • +1, notifying for upcast and downcast however, what I meant in the question was that, I am just receiving by base class ; the object is of known type (which is derived). That's why used upcasting. – iammilind Jun 10 '11 at 03:45
1

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533