/////////////////////////////////////////////////////////////// // equiv.cpp - demonstrates syntax equivalences // /////////////////////////////////////////////////////////////// #include class X { public: X(); X(const X &x); ~X(); X& operator=(const X &x); void speak(); private: static int count; int myCount; }; int X::count = 0; //----< void ctor >-------------------------------------------- X::X() : myCount(++count) { cout << " void ctor\n"; } //----< copy ctor - nothing to copy for these objects >-------- X::X(const X &x) : myCount(++count) { cout << " copy ctor\n"; } //----< dtor >------------------------------------------------- X::~X() { cout << " dtor\n"; } //----< assignment - nothing to assign for these objects >----- X& X::operator=(const X &x) { if(this==&x) return *this; cout << " assignment operator\n"; return *this; } //----< display count >---------------------------------------- void X::speak() { cout << " object #" << myCount << endl; } // //====< test stub >============================================ void main() { cout << " demonstration of equivalent syntaxes \n" << "======================================\n"; //----< different ways of calling void constructor >----------- X x1; // void construction calls X(); x1.speak(); // X x2(); // interpreted as a function declaration // x2.speak(); X x3[2]; // void construction calls X() twice x3[0].speak(); x3[1].speak(); X* ptr = new X; // void construction calls X(); ptr->speak(); delete ptr; // destructor calls ~X() ptr = new X[2]; // void construction calls X() twice ptr->speak(); (ptr+1)->speak(); //----< different ways of calling copy constructor >----------- X x4 = x1; // copy construction calls X(const X &x); x4.speak(); X x5(x1); // " " " " x5.speak(); X x6[2] = {x1,x4}; // " " " " twice x6[0].speak(); x6[1].speak(); ptr = new X(x1); // " " " " ptr->speak(); delete ptr; // destructor calls ~X() // ptr = new X(x1)[2]; // can't copy into heap array this way // ptr = new X[2] = {x1,x2}; // this doesn't work either //----< equivalent ways of calling an operator >--------------- x5 = x1; // assignment calls X& operator(const X &x); x5.operator=(x1); // " " " " }