Sobes.tech
Junior — Senior

Destructor issues when deleting through a base class pointer

livecode

Task condition

Describe the problem that occurs when deleting objects through a pointer to the base type (Base*). What will be the result of executing delete baseChild; and delete baseChildChild;? Explain why such behavior is considered dangerous.

struct Base {
    virtual void baseFunc0() {
        std::cout << "Base::baseFunc0" << std::endl;
    }
};

struct Child : Base {
    void baseFunc0() override {
        std::cout << "Child::baseFunc0" << std::endl;
    }
};

struct ChildChild : Child {
    void baseFunc0() override {
        std::cout << "ChildChild::baseFunc0" << std::endl;
    }
};

void run() {
    Base base;
    Base* baseChild = new Child;
    Base* baseChildChild = new ChildChild;

    base.baseFunc0();
    baseChild->baseFunc0();
    baseChildChild->baseFunc0();

    delete baseChild;
    delete baseChildChild;
}