Frion3L
Frion3L

Reputation: 1522

Downcasting a non pointer with reference

I would like to know the child type of a parent class. The problem is the parent class I'm getting is returned from a function by reference &. I could not resolve it. Here is an example of piece of code of what is going on:

class A : public B { ... }

B& getB() { return _b; }

main ()
{
    ...
    B aux = getB(); //this already gives me problems
    // ?? now what I have to do to know if B is a an A?
}

Thanks

Upvotes: 1

Views: 209

Answers (1)

Komi Golov
Komi Golov

Reputation: 3471

Seeing as you define aux to be a B, it really will be a B, even if getB actually returned a reference to an A. This is called slicing, and is almost certainly not what you want; there's no way to undo it.

The reason it happened is that you copied the return value of getB. If, instead, you bound a reference like this

B& aux = getB();

then aux would simply refer to whatever getB had returned. If you're sure that the reference getB returned was bound to an A you can use static_cast<A&>(aux) to access the A parts of it. If you're not sure, but if you know B has at least one virtual function, you can use dynamic_cast<A&>(aux); it'll throw an exception if it fails.

That said, if you have a reference or pointer to a base type, trying to find out what derived type it secretly refers to is often a sign of bad design. What happens if the value is of a type you didn't know about yet? There's a good chance you wanted to put this logic into a virtual member function, or perhaps wanted a more union-like structure.

Upvotes: 4

Related Questions