I am tasked to have a class C
which automatically keeps track of the number of its instances that exists, and to have a function that returns this number.
Here is what I have:
class C{
public:
static int num;
C(){ num;}
~C(){--num;}
int get_number_objs(){return num;}
};
int C::num = 0;
Does this do the trick?
This looks straightforward and might make sense, but I'm wondering if there are edge cases where you mess around with pointers or something like that where something falls through the cracks.
This is a solution verification more than anything else.
CodePudding user response:
Does this do the trick?
Almost. You also need to increment num
inside of the class's copy constructor, as well as the move constructor in C 11 and later.
Also, there is no point in having get_number_objs()
if num
is public
, but since that does expose num
to tampering from outside, num
should be private
instead. And get_number_objs()
should be static
.
Try this:
class C{
private:
static unsigned num;
public:
C(){ num; }
C(const C&){ num; }
C(C&&){ num; }
~C(){ --num; }
static unsigned get_number_objs(){ return num; }
};
unsigned C::num = 0;
Alternatively, in C 17 and later, you can inline
the num
variable so you don't have to define it separately outside of the class:
class C{
private:
static inline unsigned num = 0;
public:
C(){ num; }
C(const C&){ num; }
C(C&&){ num; }
~C(){ --num; }
static unsigned get_number_objs(){ return num; }
};