简体   繁体   中英

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
};

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();

Why casting? Just do this if you want to call Window's onResize(),

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

Alright, you can do this same, using static_cast also, but you've to do this way,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM