123456789101112131415161718192021222324252627282930313233343536373839404142434445
#include <iostream> using namespace std; struct Foo { static int ctr; int m_objNr; Foo() { m_objNr = ++ctr; cout << "Object "<< m_objNr << ": I'm the default constructor.\n"; } Foo( Foo& other) { m_objNr = ++ctr; cout << "Object "<< m_objNr << ": I'm the copy constructor.\n"; } Foo operator= ( Foo& other) { cout << "Object " << m_objNr << ": I'm the assignment operator.\n"; return other; } ~Foo() { cout << "Object " << m_objNr << ": I'm the destructor.\n"; } }; int main() { Foo::ctr = 0; Foo foo; std::cout << "--------\n"; Foo bar = foo; std::cout << "--------\n"; foo = bar; std::cout << "--------\n"; }
Foo::ctr
int Foo::ctr = 42; // initialize it here too (or don't and it will automatically initialize to zero)
1234
Foo operator= (const Foo& other) { cout << "Object " << m_objNr << ": assignment operator.\n"; return *this; }