How do you implement this Python idiom in C++

Noah Roberts roberts.noah at gmail.com
Thu Jul 27 13:06:09 EDT 2006


alainpoint at yahoo.fr wrote:

> I am no C++ expert but i guess there might be some in the Python and
> C++ newsgroups.
>

Provide compilable code that exibits your problem.  The technique is
sound; you must be screwing up somehow.


#include <iostream>

using namespace std;

template <typename T>
class counted
{
  static int count;

public:
  counted() { ++ count; }
  counted(const counted<T> &) { ++ count; }
  virtual ~counted() { -- count; }
  static int getCount() { return count; }
};

template <typename T>
int counted<T>::count = 0;

class C1 : public counted<C1>
{
public:
  C1() : counted() {}
};

class C2 : public counted<C2>
{
public:
  C2() : counted() {}
};

int main(void)
{
  C1 c11;
  C1 c12;
  C2 c2;

  cout << C1::getCount() << endl;
  cout << C2::getCount() << endl;

  int c;
  cin >> c;

  return 0;
}


output is 2 and 1 as expected.  Removing the constructors in the
derivatives doesn't change that fact.




More information about the Python-list mailing list