Caster Caster - 26 days ago 8
C++ Question

What's wrong with this c++ program? it core dump

why it core dump? It first call derived's foo, in the method of foo, it call the base's foo, right?

struct base {
virtual void foo() {};
};

struct derived : public base {
void foo() { base:foo(); }
};

int main() {
base* b = new derived();
b->foo();

delete b;
}

Answer

The program crashes, because the stack overflows. And this is because you call foo() recursively forever

struct derived : public base {
    void foo() { base:foo(); }
};

The important part is base:foo();, see the missing colon? This is the same as a label and then calling foo();

base:
    foo();

Unrelated, when you build this with gcc and option -Wall, you will get two warnings

   a.cpp: In member function 'virtual void derived::foo()':
    a.cpp:6:18: warning: label 'base' defined but not used [-Wunused-label]
         void foo() { base:foo(); }
              ^
    a.cpp: In function 'int main()':
    a.cpp:13:12: warning: deleting object of polymorphic class type 'base' which has non-virtual destructor might cause undefined behaviour         [-Wdelete-non-virtual-dtor]
         delete b;
                ^
Comments