Deleting downcast not invoking destructor - any idea?

This is a discussion on Deleting downcast not invoking destructor - any idea? within the C++ Programming forums, part of the General Programming Boards category; OK, here is the prob. I create a class, A, and B as a derived class thereof. When I use ...

  1. #1
    Evil Member
    Join Date
    Jan 2002
    Posts
    638

    Deleting downcast not invoking destructor - any idea?

    OK, here is the prob.

    I create a class, A, and B as a derived class thereof.

    When I use

    A* classAPointerThatIsActuallyB = new B;

    then the constructors for A and B are called.

    When I call a virtual from A that B overrides, the B function is called. Basic polymorphism there.

    But, when I

    delete classAPointerThatIsActuallyB;

    Only the destructor for A is called. Any ideas on how would I go about making sure that anything done by B::B() is properly undone by B::~B(), without modifying class A?

  2. #2
    Registered User
    Join Date
    May 2002
    Posts
    49
    declare ~A and ~B as virtual function.

    Remember : if any derive is needed, declare the destructor as virtual function.
    Hello, everyone.

  3. #3
    Evil Member
    Join Date
    Jan 2002
    Posts
    638
    Is there any way to do this without changing A? if my pointer knows that it is a B, is there any way to tell that to delete?

  4. #4
    Registered User
    Join Date
    May 2002
    Posts
    49
    hmm...

    then, RTTI can help you. But it is slow and complex.
    Example:

    Code:
    if(typeid(B) == typeid(*p))
        delete dynamic_cast<B*>p;
    else
        delete p;
    Compile this code with VC6, you must use /g option, or you'll receive an warn and your program will run to crash.
    Hello, everyone.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21