Thread: destructor question

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    99

    destructor question

    I've been searching for an answer here on the board about destructors. I found this
    The destructor is called either when the variable goes out of scope, or you call delete on a pointer variable.
    Is that a reason why my destructors are called twice?
    I have a base class and a derived class. I construct 3 instances of base class and three of derived class. The destructor gets called three times on the derived clas (interleaving with destructor for the base class, naturally), and then the base class destructor is called again 3 times.
    I do have pointers in both base and derived classes and I use delete on them in my own copy constructors. But if the deconstructor was called on that delete [], then my cout << "destructor" would appear much earlier in the output, right?

    I've been studying C++ for 8 weeks now, and having C as base does not help at all. It is more confusing that I would expect...

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    When you delete[] the pointers during copy construction, you are deleting pointers to ints, right? In that case, your class destructor is not called, the int destructor is called (although ints don't have destructors of course).

  3. #3
    chococoder
    Join Date
    Nov 2004
    Posts
    515
    That is as it should be.
    When an instance of a derived class is constructed first the baseclass constructor is called and after that the constructor of the derived class.
    When that instance is then destructed the derived class destructor is called and after that the baseclass destructor.

    This so any cleanup that the baseclass destructor needs to perform is taken care of.

    If your tree gets deeper, more calls result.

  4. #4
    Registered User
    Join Date
    Sep 2004
    Posts
    99
    Pheeew. That's a relief. Thanks a lot guys!

Popular pages Recent additions subscribe to a feed