Deleting array of derived class

Discussion in 'C++' started by SeniorLee, Dec 30, 2007.

  1. SeniorLee

    SeniorLee Guest

    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?
     
    SeniorLee, Dec 30, 2007
    #1
    1. Advertising

  2. SeniorLee

    Guest

    SeniorLee wrote:

    > 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
     
    , Dec 30, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    9
    Views:
    581
    justanotherguy
    Dec 3, 2004
  2. Rohit
    Replies:
    7
    Views:
    408
    Prawit Chaivong
    Mar 1, 2005
  3. Replies:
    1
    Views:
    405
    myork
    May 23, 2007
  4. Replies:
    1
    Views:
    396
    Victor Bazarov
    May 23, 2007
  5. David
    Replies:
    3
    Views:
    408
    Grizlyk
    Jan 29, 2008
Loading...

Share This Page