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

戏子无情 提交于 2019-12-05 10:51:14
James McNellis

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  ^^
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!