// demonstrates the use of copy constructor // mikhail nesterenko // 11/22/99 #include using namespace std; // just a class with two member functions class myclass{ public: myclass(); myclass(const myclass&); // copy constructor // have to pass another // object by reference (why?) // const is used for safety void setpint(int i){*pint=i;}; void printdata(); private: int *pint; }; // void constructor - allocates location for integer // variable myclass::myclass(){ pint=new int; } // copy constructor - copies the value held in the // memory location rather than the pointer myclass::myclass(const myclass &o){ pint=new int; *pint=*(o.pint); } // prints the value of the member variable void myclass::printdata(){ cout << "the value stored in the object is: "; cout << *pint; cout << endl; } // function that takes object of myclass as parameter void otherfunc(myclass); // creates an object of myclass, prints // its value int main(){ myclass ob1; ob1.setpint(1); otherfunc(ob1); ob1.printdata(); } void otherfunc(myclass p){ p.printdata(); // changing the value // stored in p // note - the value in ob1 is // not changed p.setpint(2); p.printdata(); }