Deleting array of derived class

S

SeniorLee

i had a question while i was reading the book "MEC++ chapter 3"

in the book, he says this will not work.

class BST
{
public:
virtual ~BST() { cout << "BST" << endl; }
};

class BalancedBST : public BST
{
public:
~BalancedBST() { cout << "BalancedBST" << endl; }
};

void delete(BST array[])
{
delete [] array;
}

BalancedBST *balTreeArray = new BalancedBST[10];

deleteArray(balTreeArray);


but with the VIsual C++ 2005 it seems to be worked fine

the set of "BalancedBST" and "BST" is printed 10 times.

did i understand the book wrong way? or it's just because of compiler
dependency?
 
J

jkherciueh

SeniorLee said:
i had a question while i was reading the book "MEC++ chapter 3"

in the book, he says this will not work.

class BST
{
public:
virtual ~BST() { cout << "BST" << endl; }
};

class BalancedBST : public BST
{
public:
~BalancedBST() { cout << "BalancedBST" << endl; }
};

void delete(BST array[])
{
delete [] array;
}

BalancedBST *balTreeArray = new BalancedBST[10];

deleteArray(balTreeArray);


but with the VIsual C++ 2005 it seems to be worked fine

the set of "BalancedBST" and "BST" is printed 10 times.

did i understand the book wrong way?
No.

or it's just because of compiler dependency?

Yes. You have undefined behavior, which on your platform happens to look
fine. Hint: this can be caused by the size of the base and the derived
class being equal so that vtable pointers happen to reside at the right
position; however, even though the undefined behavior could have an
explanation, it is still undefined.


Best

Kai-Uwe Bux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top