#include <iostream> using namespace std; class Widget { public: int width; virtual void resize() { width = 10; } }; class SpeWidget :public Widget { public: int height; void resize() override { //Widget::resize(); Widget* th = static_cast<Widget*>(this); th->resize(); height = 11; } }; int main() { //Widget* w = new Widget; //w->resize(); //std::cout << w->width << std::endl; SpeWidget* s = new SpeWidget; s->resize(); std::cout << s->height << "," << s->width << std::endl; std::cin.get(); } Derived class (SpeWidget) virtual function (resize()) wants to call that in base class (Widget). Why does the above code have segment fault. Thank you!
resizeisvirtual, even if you call it through aWidget*it will call the "correct" function from the derived classSpeWidget. The correct syntax for calling the method from the superclass is justWidget::resize(). That is, you write justvoid resize() override { Widget::resize(); height = 11; }, or maybevoid resize() override { this->Widget::resize(); height = 11; }, if you want.this->Widget::resize()is clear to explain it, I think.