// demonstrates the use of destructor // mikhail nesterenko // 4/3/2013 #include using std::cout; using std::endl; // 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 ~myclass(); // desctructor 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); } // destructor, deallocates the dynamic variable myclass::~myclass(){ delete pint; } // prints the value of the member variable void myclass::printdata(){ cout << "the value stored in the object is: "; cout << *pint; cout << endl; } void otherfunc(myclass); // function that takes object of myclass as parameter // by value // 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 o // note - the value in ob1 is // not changed p.setpint(2); p.printdata(); } // destructor is implicitly invoked here