-3

I'm working on a game, where i have a derived player class that inherites from a Parent GameObject Class, What i want to accomplish is calling the base class destructor inside of the derived class destructor, can i do that?

Example:

// Base Class
class A
{
    public:

        // other code goes here...

        ~A();

    protected:
        int a;
}

// ...
// ...

// Base Class Destructor
A::~A()
{
    // sets a back to 0
    a = 0;
}

// Derived Class
class B : public A
{
    public:

        // other code goes here...

        ~B();
}

// Derived Class Methods
B::~B()
{
    // Calls for Base Class Destructor, How can i accomplish this
    A::~A();

}
Nobody
  • 605
  • 1
  • 7
  • 9
  • 3
    You don't need to do that. It gets called automatically. Also, `A`'s destructor seems pointless, unless you leak a reference to `a` somehow. – juanchopanza Aug 28 '14 at 19:10
  • But bear [this](http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors) in mind. – James M Aug 28 '14 at 19:11
  • @juanchopanza so i don't need to create a derived class destructor? – Nobody Aug 28 '14 at 19:11
  • With the code you have shown, you don't need to provide any destructors at all. The compiler generated ones will do the right thing. – juanchopanza Aug 28 '14 at 19:11
  • @juanchopanza even if i have alot of initialized member propreties? Because i use the base class destructor to deallocate memory; i use textures and images in the game. – Nobody Aug 28 '14 at 19:12
  • In general yes. It depends on the "properties". The internet is full of information about when you need to provide destructors. – juanchopanza Aug 28 '14 at 19:13
  • @juanchopanza On more thing, about constructors, should i incude them even if don't have something to initialize? – Nobody Aug 28 '14 at 19:19
  • Not really. Compiler will provide default constructor if it can. – Alexey Shmalko Aug 28 '14 at 19:35

1 Answers1

1

Parent class' destructor is automatically called. Calling order of destructors is opposite to order of constructors; so that, it's ok to rely on parent class' fields in destructor of derived class.

You should better declare destructor as virtual. It's needed to determine correct destructor if you delete object of derived class through base class pointer.

Try adding trace output in destructors to ensure what calling order of destructors is.

Alexey Shmalko
  • 3,678
  • 1
  • 19
  • 35