C++ multi-inheritance, error in delete object

Viewed 118

I created this simple C++ program:

#include <iostream>

class Base1 {
public:
    virtual void method1() = 0;
};

class Base2 {
public:
    virtual void method2() = 0;
};

class B : public Base1, public Base2 {
public:
    void method1() override {
        std::cout << "method1 from B\n";
    }
    void method2() override {
        std::cout << "method2 from B\n";
    }
};

int main() {
    Base1 *x = new B;
    x->method1();
    delete x;
    return 0;
}

And it works fine. But if I change the code in main function to:

int main() {
    Base2 *x = new B;
    x->method2();
    delete x;
    return 0;
}

When I run this code, I have this runtime error: free(): invalid pointer

Why this error when I use base2 class and it works fine with base1? How can I fix it?

1 Answers

You need your base classes destructors to be virtual if you are aiming to use those polymorphically.

class base1 {
public:
    virtual ~base1() = default;
    virtual void method1() = 0;
};

class base2 {
public:
    virtual ~base2() = default;
    virtual void method2() = 0;
};

class B : public base1, public base2 {
public:
    void method1() override {
        std::cout << "method1 from B\n";
    }
    void method2() override {
        std::cout << "method2 from B\n";
    }
};
Related