A
Agent Mulder
I have a question concerning an article by Scott Meyers, C/C++ Users
Journal, April 1998, at
http://www.cuj.com/documents/s=8066/cuj9804meyers/
He explains how to count objects of a given type. Inheritance is preferred
over containment, but then the "old virtual destructor spiel" comes up. Read
it. Now my silly question is, why is the destructor not declared virtual in
the template?
Here is a quote from the article:
<quote>
We can get the behavior we want by employing one of the best-known but
oddest-named tricks in all of C++: we turn Counter into a template, and each
class using Counter instantiates the template with itself as the template
argument.
Let me say that again. Counter becomes a template:
template<typename T>
class Counter {
public:
Counter() { ++count; }
Counter(const Counter&) { ++count; }
~Counter() { --count; }
static size_t howMany()
{ return count; }
private:
static size_t count;
};
template<typename T>
size_t
Counter<T>::count = 0; // this now can go in header
</quote>
The above becomes:
template<typename T>
class Counter {
public:
Counter() { ++count; }
Counter(const Counter&) { ++count; }
virtual ~Counter() { --count; }
static size_t howMany()
{ return count; }
private:
static size_t count;
};
template<typename T>
size_t
Counter<T>::count = 0; // this now can go in header
-X
Journal, April 1998, at
http://www.cuj.com/documents/s=8066/cuj9804meyers/
He explains how to count objects of a given type. Inheritance is preferred
over containment, but then the "old virtual destructor spiel" comes up. Read
it. Now my silly question is, why is the destructor not declared virtual in
the template?
Here is a quote from the article:
<quote>
We can get the behavior we want by employing one of the best-known but
oddest-named tricks in all of C++: we turn Counter into a template, and each
class using Counter instantiates the template with itself as the template
argument.
Let me say that again. Counter becomes a template:
template<typename T>
class Counter {
public:
Counter() { ++count; }
Counter(const Counter&) { ++count; }
~Counter() { --count; }
static size_t howMany()
{ return count; }
private:
static size_t count;
};
template<typename T>
size_t
Counter<T>::count = 0; // this now can go in header
</quote>
The above becomes:
template<typename T>
class Counter {
public:
Counter() { ++count; }
Counter(const Counter&) { ++count; }
virtual ~Counter() { --count; }
static size_t howMany()
{ return count; }
private:
static size_t count;
};
template<typename T>
size_t
Counter<T>::count = 0; // this now can go in header
-X