Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question of using static_cast on "this" pointer in a derived object to base class

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
};
like image 560
Johnyy Avatar asked Dec 28 '10 04:12

Johnyy


People also ask

What is the use of static_cast in C++?

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.

Is static_cast backwards compatible with C?

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.

What happens when you perform a static_cast?

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).

Does static_cast create a copy?

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!


1 Answers

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();
like image 179
James McNellis Avatar answered Oct 02 '22 00:10

James McNellis