Ofer
Ofer

Reputation: 289

Issue with Using Polymorphism While Only Child Class has a Virtual Method

Does the following code violate the C++11 standard in any way? I get a failed assertion in VC++ 2013.

class P {};

class C : public P
{
public:
    virtual void a() {}
};

int main()
{
    P* p = new C();
    delete p;
}

The failed assertion is:

File: f:\dd\vctools\crt\crtw32\misc\dbgdel.cpp
Line: 52

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

Upvotes: 2

Views: 213

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

Yes,

delete p;

has Undefined Behavior since the dynamic type of the pointee is different from the statically known type, and the latter doesn't have a virtual destructor.

C++11 §5.3.5/3:

In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined

Upvotes: 8

Related Questions