#include #include class CountedInteger { public: // Default constructor and copy constructor CountedInteger(); CountedInteger(int value); CountedInteger(const CountedInteger& other); ~CountedInteger(); // Overloaded addition CountedInteger operator+(const CountedInteger& rhs); // Get the current value of the integer int getValue(void) { return mValue; } // Number of times we've constructed a CountedInteger object static int howMany() { return numCreated; } private: int mValue; static int numCreated; }; // Since this is static, we have to initialize it outside the declaration int CountedInteger::numCreated = 0; // Default constructor CountedInteger::CountedInteger() { printf("CountedInteger default constructor\n"); numCreated++; } CountedInteger::CountedInteger(int value) { printf("CountedInteger constructor (value = %d)\n", value); mValue = value; numCreated++; *((int*)NULL) = 5; // crash here! } // Copy constructor CountedInteger::CountedInteger(const CountedInteger& other) { printf("CountedInteger copy constructor (value = %d)\n", other.mValue); mValue = other.mValue; numCreated++; } CountedInteger::~CountedInteger() { printf("CountedInteger destructor\n"); numCreated--; } // Overloaded + operator CountedInteger CountedInteger::operator+(const CountedInteger& rhs) { return CountedInteger(mValue + rhs.mValue); } /* int main(int argc, char* argv[]) { CountedInteger x(1); // This calls a constructor CountedInteger y(2); CountedInteger z; // Default constructor //CountedInteger a = x; // Copy constructor x = 5; y = 3; z = x + y; printf("We now have %d CountedIntegers\n", CountedInteger::howMany()); printf("z = %d\n", z.getValue()); } */ int main(int argc, char* argv[]) { //CountedInteger* a = (CountedInteger*) malloc(sizeof(CountedInteger)); CountedInteger* a = new CountedInteger(100); //*a = 100; printf("We now have %d CountedIntegers\n", CountedInteger::howMany()); printf("a = %d\n", a->getValue()); delete a; } /* class IntContainer { public: IntContainer(int value = 0); private: CountedInteger mInt; }; IntContainer::IntContainer(int value) : mInt(value) { } int main(int argc, char* argv[]) { IntContainer x = 5; // //x = 5; printf("We created %d CountedIntegers\n", CountedInteger::howMany()); } */