Caster
Caster

Reputation: 58

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;
}

Upvotes: 1

Views: 83

Answers (3)

BinWone
BinWone

Reputation: 23

You lose a ':'.

base:foo(); should be base::foo();

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92321

You are missing a colon in base:foo();, oddly enough turning it into a label and a recursive call.

void foo()
{ 
   base:
     foo();
 }

Add a second : to make it a call to the base class function base::foo();

Upvotes: 6

Olaf Dietsche
Olaf Dietsche

Reputation: 74078

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;
                ^

Upvotes: 6

Related Questions