Stop Microsoft

Miscellaneous => Programming & Networking => Topic started by: anphanax on 28 May 2005, 04:58

Title: Virtual Destructors?
Post by: anphanax on 28 May 2005, 04:58
I got a C++ question.

Why is this legal:
virtual ~classname(void)

When this isn't:
virtual classname(void)

I have yet to figure out a way to override a destructor for a base class, that's why i'm asking.
Title: Re: Virtual Destructors?
Post by: muzzy on 28 May 2005, 13:18
The latter is a construtor, not a destructor. It doesn't make sense to have a virtual constructor, because virtual methods are a mechanism for call indirection, to invoke the method of actual class instead of the referenced one. Construction is a process where this doesn't happen, so you cannot declare constructors virtual.

Regarding virtual destructors, what's the problem? Just define a new destructor in the descendant class once base class destructor has been declared virtual and you'll be fine.
Title: Re: Virtual Destructors?
Post by: muzzy on 28 May 2005, 13:26
Since I don't quite get what's your problem, I figured I'd write a short example code to show how it should work. Please be more specific in asking questions if this doesn't help you.

Code: [Select]

#include
#include

using namespace std;

struct Foo {
  Foo() { cout << "Foo()" << endl; }
  virtual ~Foo() { cout << "~Foo()" << endl; }
};

struct Bar : Foo {
  Bar() { cout << "Bar()" << endl; }
  ~Bar() { cout << "~Bar()" << endl; }
};

int main()
{
  auto_ptr f(new Bar);
  cout << "main()" << endl;
}