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

2

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
};
Resistencia answered 28/12, 2010 at 4:34 Comment(1)
I would remark that since static_cast<Window>(*this) creates a copy, this code is most likely NOT producing the intended result.Onetoone
I
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();
Isagoge answered 28/12, 2010 at 4:36 Comment(1)
No, it is the same as Window w(*this);.Radiography
F
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  ^^
Fonz answered 28/12, 2010 at 6:50 Comment(4)
That would be true if the OP had used: static_cast<Window&> (Notice the & here and the lack of it in the above example).Immanuel
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).Immanuel
Why did you use a reference?Assuan
@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.Fonz

© 2022 - 2024 — McMap. All rights reserved.