Jump to content
  • Advertisement
Sign in to follow this  
TTK-Bandit

[c++] Destructor Weirdness

This topic is 3034 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a weird problem:
class Other {
public:
Other() { printf("Other()\n"); }
~Other() { printf("~Other()\n"); }
};
class Base {
public:
Base() { printf("Base()\n"); }
virtual ~Base() { printf("~Base()\n"); }
};

class Derived : public Base {
public:
Derived() { printf("Derived()\n"); }

protected:
Other value;
};

int main( int argc, char* argv[] ) {
Base *b = new Derived;
delete b;
return 0;
}


output:
Base()
Other()
Derived()
~Other()
~Base()

but if the virtual destructor of the Base class is removed, the destructor of the Other class will never be called.
output:
Base()
Other()
Derived()

Any ideas why ? (vc++ 2008)
I always thought virtual would only affect the class itself and its derived classes, but not the destruction of the members.

Share this post


Link to post
Share on other sites
Advertisement
If ~Base is not virtual the compiler cannot call the correct destructor for the class and calls just ~Base instead of ~Derived. ~Derived is responsible for freeing the instance of Other. This is why you should generally specify a virtual destructor (even if completely empty) for a class which is meant as a base class (provided the destructor is indeed empty this is not a violation of the Rule of Three).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!