Giving Each Instance of a Class a Unique Identifier - C++ Class

C++ examples for Class:static member

Description

Giving Each Instance of a Class a Unique Identifier

Demo Code

                                                        
#include <iostream>
                                                        
class MyClass {/* w  w w. j a  va  2  s  . c  om*/
protected:
   static int nextID;
public:
   int id;
   MyClass();
   MyClass(const MyClass& orig);
   MyClass& operator=(const MyClass& orig);
};
                                                        
int MyClass::nextID = 0;
                                                        
MyClass::MyClass() {
   id = ++nextID;
}
                                                        
MyClass::MyClass(const MyClass& orig) {
   id = orig.id;
}
                                                        
MyClass& MyClass::operator=(const MyClass& orig) {
   id = orig.id;
   return(*this);
}
                                                        
int main() {
   MyClass a;
   std::cout << a.id << std::endl;
   MyClass b;
   std::cout << b.id << std::endl;
   MyClass c;
   std::cout << c.id << std::endl;
}

Result


Related Tutorials