In More effective C++ Meyers has described a way to count the instantiation of the objects using an object counting base class (item 26). Is it possible to implement the same using composition technique as below . Is there a specific advantage using private inheritance and what are the drawbacks of using composition in this case.
ps:- I have reused the code from More effective C++ with small modification.
#ifndef COUNTERTEMPLATE_HPP_
#define COUNTERTEMPLATE_HPP_
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
template <class BeingCounted>
class Counted {
public:
static int ObjectCount(){return numOfObjects;}
Counted();
Counted(const Counted& rhs);
~Counted(){--numOfObjects;}
protected:
private:
static int numOfObjects;
static int maxNumOfObjects;
void init();
};
template<class BeingCounted> Counted<BeingCounted>::Counted()
{
init();
}
template<class BeingCounted> Counted<BeingCounted>::Counted(const Counted& rhs)
{
init();
}
template<class BeingCounted> void Counted<BeingCounted>::init()
{
if(numOfObjects>maxNumOfObjects){}
++numOfObjects;
}
class Printer
{
public:
static Printer* makePrinter(){return new Printer;};
static Printer* makePrinter(const Printer& rhs);
Counted<Printer>& getCounterObject(){return counterObject;}
~Printer();
private:
Printer(){};
Counted<Printer> counterObject;
Printer(const Printer& rhs){};
};
#endif /* COUNTERTEMPLATE_HPP_ */