How do you implement this Python idiom in C++ ?

A

alainpoint

Hello,

I have the need to write the equivalent of Python class methods in C++.
Chuck Allison proposes the following
(http://www.artima.com/cppsource/simple.html):
#include <iostream>
using namespace std;

// A base class that provides counting
template<class T> class Counted {
static int count;
public:
Counted() { ++count; }
Counted(const Counted<T>&) { ++count; }
~Counted() { --count; }
static int getCount() { return count; }
};

template<class T> int Counted<T>::count = 0;

// Curious class definitions
class CountedClass : public Counted<CountedClass> {};
class CountedClass2 : public Counted<CountedClass2> {};

It apparently works but in fact it doesn't:
If you derive from such a class, you get the count of the parent class,
not of the derived class.
class CountedClass3 : public CountedClass {};

int main() {
CountedClass a;
cout << CountedClass::getCount() << endl; // 1
CountedClass b;
cout << CountedClass::getCount() << endl; // 2
CountedClass3 c;
cout << CountedClass3::getCount() << endl; // 3 and should be 1
cout << CountedClass::getCount() << endl; // 3 and should be 2
}

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

Alain
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top