Question of using static_cast in the "this" pointer in a derived object for a base class

this is an example taken from Effective C ++ 3ed, it says that if this is static_castused in this way, the base part of the object is copied and the call is called from that part. I wanted to understand what was going on under the hood, would 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
};
+5
source share
2 answers

It:

static_cast<Window>(*this).onResize();

is the same:

{
    Window w = *this;
    w.onResize();
}   // w.~Window() is called to destroy 'w'

The first line creates a copy of the subobject of the base class of the Windowobject SpecialWindowthat it points to this. The second line calls onResize()in this copy.

: Window::onResize() , this; Window::onResize() this, . , this, .

Window::onResize() , this, , :

Window::onResize();
+11

? , Window onResize(),

Window::onResize(); //self-explanatory!

, , static_cast, ,

   static_cast<Window&>(*this).onResize();
    //note '&' here  ^^
+5

All Articles