I'm reading Effective C++ and came across this example:
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
...
};
The book says:
What you might not expect is that it does not invoke that function on the current object! Instead, the cast creates a new, temporary copy of the base class part of *this, then invokes onResize on the copy!
Why does static_cast (above code) create a new copy? Why not just just use the base class part of the object?
static_cast<Window&>(*this).onResize();
, then I think it would use the current object. (Note the&
). Not sure though. – Wun