Dean Seo
Dean Seo

Reputation: 5683

An error when you override non-virtual-function in C++

When you override a member function that is not virtual in a class with no virtual functions, VS compilers occurs the "_BLOCK_TYPE_IS_VALID" error.

For example,

class A{
public:
    int a;
public:
    void func(){}
    ~A(){}
};

class B : public A{
public:
    virtual void func(){}

    ~B(){}
};

int main(void){
    A* a = new B();
    delete a;  // error!

    return 0;
}

I guess this is because in main(), the a has vtable but the compiler misses it and can't get the exact size of the header?

Somebody can get my curiosity about this shattered?

Thanks in advance.

Upvotes: 0

Views: 338

Answers (2)

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

You're trying to destroy an object using pointer to the base class, but the destructor is not virtual. If a class is part of a inheritance hierarchy, always make dtors virtual.

Upvotes: 1

ephemient
ephemient

Reputation: 204758

You can remove A::func() and the program is still erroneous.

The real reason is that A::~A() (not B::~B()) is being called on an object of type B.

See C++ FAQ § 20.7 "When should my destructor be virtual?"

Upvotes: 4

Related Questions