Bryan YU
Bryan YU

Reputation: 77

Virtual function of derived class calls that of base class

#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!

Upvotes: 0

Views: 412

Answers (1)

Joe
Joe

Reputation: 6796

The commented out code is right.

Widget::resize();

Your substitute code is wrong.

Widget* th = static_cast<Widget*>(this);
th->resize();

Think about it: You are calling a virtual function through a pointer to the base class. What happens when you do that with any virtual function? It calls the most derived version. In other words, endless recursion.

Upvotes: 1

Related Questions