Jaco
Jaco

Reputation: 1

Getting error "Debug Assertion Failed"

I have a vector of pointers to a class I created called polygon, which has derived classes for different shapes. The relevant code looks something like this:

int main() {
vector<polygon*> polygonVec;

polygonVec.push_back(new triangle(2,3,1,2,-1,-4, "triangle 1"));
polygon *tempPolygon;
tempPolygon = new rectangle(1,2,3,4,5,6,7,8, "rectangle 1");
polygonVec.push_back(tempPolygon);


for(vector<polygon*>::iterator itr = polygonVec.begin();
    itr != polygonVec.end();
    itr++)
{
    cout<<*itr<<endl;
}

for(vector<polygon*>::iterator itr = polygonVec.begin();
    itr != polygonVec.end();
    itr++)
{
    delete *itr;
}

polygonVec.clear();

When I compile and run it in Visual Studio 2012, it runs as expected and gives the required output, but then it throws below error at the end

"Debug Assertion Failed … _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)".

Can anybody tell me why this is happening?

Upvotes: 0

Views: 79

Answers (1)

vsoftco
vsoftco

Reputation: 56547

Make sure that you declare your polygon destructor virtual, as otherwise you have undefined behaviour when you try invoking delete on a polymorphic object via a pointer to base.

Upvotes: 1

Related Questions