this is an example taken from Effective C++ 3ed, it says that if the static_cast
is used this way, the base part of the object is copied, and the call is invoked from that part. I wanted to understand what is happening under the hood, will anyone help?
class Window { // base class
public:
virtual void onResize() { } // base onResize impl
};
class SpecialWindow: public Window { // derived class
public:
virtual void onResize() { // derived onResize impl;
static_cast<Window>(*this).onResize(); // cast *this to Window,
// then call its onResize;
// this doesn't work!
// do SpecialWindow-
} // specific stuff
};
The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.
Since C++ is 99% backwards-compatible with C, most C source code can be compiled as C++ source code and will work, and in that scenario, static_cast could be part of the code and would compile.
Static Cast: This is the simplest type of cast which can be used. It is a compile time cast.It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones).
What you might not expect is that it does not invoke that function on the current object! Instead, the cast creates a new, temporary copy of the base class part of *this, then invokes onResize on the copy!
This:
static_cast<Window>(*this).onResize();
is effectively the same as this:
{
Window w = *this;
w.onResize();
} // w.~Window() is called to destroy 'w'
The first line creates a copy of the Window
base class subobject of the SpecialWindow
object pointed to by this
. The second line calls onResize()
on that copy.
This is important: you never call Window::onResize()
on the object pointed to by this
; you call Window::onResize()
on the copy of this
that you created. The object pointed to by this
is not touched after you make the copy it.
If you want to call Window::onResize()
on the object pointed to by this
, you can do so like this:
Window::onResize();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With