How to restart level when player dies

Virtual functions can have a definition. Even pure virtual functions can have a definition, but they don’t have to. If you somehow call a pure virtual function with no definition, then the runtime exception will happen.

Typically, this happens if you attempt to call the superclass function in some way that’s not caught by the compiler/linker (a direct reference will cause a linker error, but a constructor or destructor reference may cause it to happen.)

#include <iostream>

using namespace std;

void func(struct Foo *f);

struct Foo {
    Foo() { cout << "Foo::Foo()" << endl; }
    virtual ~Foo() { cout << "Foo::~Foo()" << endl; func(this); }
    virtual void pure_impl() = 0;
    virtual void pure_not_impl() = 0;
};

void Foo::pure_impl() { cout << "Foo::pure_impl()" << endl; }

struct Bar : Foo {
    Bar() { cout << "Bar::Bar()" << endl; }
    ~Bar() { cout << "Bar::~Bar()" << endl; pure_not_impl(); }
    void pure_impl() override { cout << "Bar::pure_impl()" << endl; Foo::pure_impl(); }
    void pure_not_impl() override { cout << "Bar::pure_not_impl()" << endl; }
};

void func(Foo *f) {
    f->pure_impl();
    f->pure_not_impl();
}

int main() {
    Bar b;
    func(&b);
    return 0;
}

2 Likes