Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shivajichalise/2919c2d41cb6834235ed110e3ec34ebb to your computer and use it in GitHub Desktop.
Save shivajichalise/2919c2d41cb6834235ed110e3ec34ebb to your computer and use it in GitHub Desktop.
Object Counter in C++
/*CRTP -> Curiously recurring template pattern*/
/*
CRTP is when a class A has a base class which is a template specialization for the class A itself.
eg:
template <class T>
class X{...};
class A : public X<A> {...};
(source: https://stackoverflow.com/questions/4173254/what-is-the-curiously-recurring-template-pattern-crtp)
*/
#include <iostream>
using namespace std;
template <class T>
class Demo{
private:
static int count;
public:
Demo(){
count++;
}
Demo(const Demo &d){
count++;
}
~Demo(){
count--;
}
static int GetCount(){
return count;
}
};
template<class T>
int Demo<T>::count = 0;
class MyClass : private Demo<MyClass>{
public:
using Demo<MyClass>::GetCount;
};
int main(){
MyClass m;
MyClass m1;
MyClass m2;
cout << "Total no of objects created: " << m.GetCount() << endl;
return 0;
}
/* (cource: https://stackoverflow.com/questions/1926605/how-to-count-the-number-of-objects-created-in-c) */
#include <iostream>
using namespace std;
class Demo{
private:
static int objCount;
protected:
int num;
char a[20];
public:
Demo(){
objCount++;
}
static void printCount(){
cout << "Total number of objects created: " << objCount;
}
void echo(){
cout << "Hello World" << endl;
}
};
int Demo :: objCount = 0;
int main()
{
Demo d;
d.echo();
Demo d1;
Demo d2;
d.printCount();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment