Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static/dynamic cast of references/objects

I was playing around with a bunch of casting operators a while ago, which apparently I did not really get at the time. I was looking over my code now and I saw this:

Base(Derived &p_derived) : m_state(static_cast<Base>(p_derived).m_state){}

I think I have now got a better understanding of casting of pointers and references thanks to a very good answer here on stackoverflow, but now there's objects involved. What exactly happens when the reference is casted to an object? Or what if p_derived was the object itself and not just a reference? Would it be creating new objects and if so, how would these be instanciated?

I'm also surprised that this could be compiled at all since in Base.h, where this code is found, Derived is only forward declared meaning it shouldn't know that it actually derives from Base. I tried at another place to do a static cast from a Derived* to a Base*, but that would rightfully not compile due to the types being incompatible as far as that translation unit was concerned.

like image 623
user1130005 Avatar asked Jan 17 '23 18:01

user1130005


1 Answers

When you use a reference, you're generally actually using the object it refers to. That's the magic transparency of reference syntax that you don't get with pointers; arguably it's their reason for being.

This scenario is no exception: you're taking the p_derived referee and constructing a new Base out of it via slicing.

static_cast<Base&>(p_derived) will cast the reference itself, if that's what you're after (and even if it's not :P).

I'm also surprised that this could be compiled at all since in Base.h, where this code is found, Derived is only forward declared meaning it shouldn't know that it actually derives from Base.

Yea, that surprises me, too. Are you sure? (Demo / Demo - not sure which you're using)

like image 152
Lightness Races in Orbit Avatar answered Jan 24 '23 13:01

Lightness Races in Orbit