Sunday, 29 September 2013

The static member in a nested class

Sometimes, it is desired to track the number of objects created on the heap by a particular class. Suppose class A_outer has a nested class A_inner. A_outer creates objects of A_inner on the heap. Is it possible to track how many A_inner objects were created by an instance of A_outer using a static member in A_inner?

It is tempting to think that the static member in the A_inner class "belongs" to an instance of A_outer, as follows:

instance1 of A_outer
-instance1 of A_inner
-instance2 of A_inner
-static member Count of A_inner "in instance1 of A_outer" = 2

instance2 of A_outer
-instance1 of A_inner
-instance2 of A_inner
-instance3 of A_inner
-static member Count of A_inner "in instance2 of A_outer" = 3

Unfortunately, the A_inner class is actually a class just like any other, and so there is only ONE value of the static member. Thus, by the time instance3 of A_inner was created, the value of Count would have been 5!

In fact, an easy way to remember this is to look at the initialization of the static member:

int A_outer::A_inner::Count = 0;

which does not distinguish which instance (of A_outer) it is referring to (or whether one even exists in the first place).

P.S. How should the counting be accomplished, then? One obvious way is to use a member in A_outer. To address the concern of "forgetting to increase the count", consider using a method Create_A_inner to create the inner instance and increase the count.

No comments:

Post a Comment