I am looking at a piece of code where there's a c-style cast that puzzles me.
I am fairly familiar with casting, but this one I really can't grasp. So, here it is: I have two classes, say Base and Derived, but Derived does not add any method/attribute. Basically it's just a particular case of Base when one of its attributes (call it M_blockSize) is fixed to 1; however, none of the methods requires a particular implementation nor there is an extension of functionalities. The benefit of such Derived class is not the point of this thread. Let's assume the developers had their good reasons for this.
Anyway, in the piece of code I'm looking something like this happens:
void foo(const Derived& d){...}
[...]
Base b;
foo((Derived&) b);
So, the developers casted the base object into a reference to a derived one. In my understanding, downcasting is done if the concrete type of the "castee" (b) is indeed Derived. Which is not the case here.
However, this is c-style cast, so the compiler is trying a whole bunch of casts and I don't know which one it eventually works.
So, questions:
- 1) what casting is the compiler doing? I'm assuming a reinterpret_cast maybe?
- 2) would static_cast< Derived& >(b) work as well?
- 3) if class Derived added some methods/attributes (not used in foo), would this still work?
- 4) is the key point that foo does not use any functionality of Derived that is not already in Base?
I hope the question is clear. Thank you for your help.