Counter object as class data member
I am reading Counting Objects in C ++ from Scott Meyers: http://www.drdobbs.com/cpp/counting-objects-in-c/184403484 . It defines a class Counter
:
class Counter {
public:
Counter() { ++count; }
Counter(const Counter&) { ++count; }
~Counter() { --count; }
static size_t howMany()
{ return count; }
private:
static size_t count;
};
// This still goes in an
// implementation file
size_t Counter::count = 0;
The article says that one of the ways to use this class is the data member of the class:
class Widget {
public:
..... // all the usual public
// Widget stuff
static size_t howMany()
{ return Counter::howMany(); }
private:
..... // all the usual private
// Widget stuff
Counter c;
};
My question is about expression Counter c;
. If we are using a static method Counter
, why is the Counter
object declared internally Widget
?
source to share
The reason an object works Counter
is because it does its job in its constructors and destructors. If you want to Widget
be used Counter
for counting, you need to make sure that the constructors Widget
call the constructors Counter
, and also that the Widget
destructor calls the Counter
destructor.
This can be done by making it a Counter
member of the instance Widget
. Although it Widget
never Counter
invokes methods explicitly, C ++ confidently invokes constructor and destructor invocations Counter
implicitly as long as it Counter
is a data member of the class Widget
. Note that making Counter
a a static
member Widget
would not achieve the same goal because calls to the constructor and destructor on the instance are Widget
not redirected to its members static
.
source to share
The real solution is slightly below the line of the article. The code you posted is for the ultimate purpose of illustration only. This is not a real solution.
The real solution is to make Counter
a class 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;
And then use it as the parent class of classes for which you want to count objects.
// inherit from Counter to count objects
class Widget: public Counter<Widget> {
.....
};
I am adding this as an extension. This does not appear in the article you linked to.
// inherit from Counter to count objects
class Foo: public Counter<Foo> {
.....
};
Now functions Widget
and Foo
have functionality.
source to share