5

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
};
James McNellis
  • 348,265
  • 75
  • 913
  • 977
Johnyy
  • 2,056
  • 3
  • 22
  • 28
  • 2
    I would remark that since `static_cast(*this)` creates a copy, this code is most likely **NOT producing the intended result**. – gatopeich Mar 22 '11 at 10:29

2 Answers2

12

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();
Community
  • 1
  • 1
James McNellis
  • 348,265
  • 75
  • 913
  • 977
6

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  ^^
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • That would be true if the OP had used: `static_cast` (Notice the & here and the lack of it in the above example). – Martin York Dec 28 '10 at 08:06
  • 1
    What I was trying to say. Was your first version is not equivalent to the OP. This is because the OP version does not use reference and thus creates a copy of (*this) (using the copy constructor) then calls onResize() on the copy (not the current object). – Martin York Dec 28 '10 at 09:19
  • Why did you use a reference? – Owl66 Oct 17 '20 at 21:38
  • @Lexshard: So that the `static_cast` does not create a copy, in which case it'll call `onResize()` on the copied object which gets destroyed immediately, and the original object remains unchanged. Hope that helps. – Nawaz Oct 18 '20 at 16:11