//freestore.cpp //how to use the freestore #include //cout, cin, endl //istream, ostream using namespace std; #include //setw class Pairs { public: Pairs() {cout << "Making a pair.\n"; set();} ~Pairs() {cout << "destroying the pair " << *this << endl;} void set (int xval=0, int yval=0) //default parameters {x=xval; y=yval;} private: int x,y; //friends aren't member functions //but are given the key to private //data and private functions. friend istream& operator>>(istream& infile, Pairs& p); friend ostream& operator<<(ostream& outfile, Pairs & p); }; //end pairs //implementation of pairs friend functions //Since not members, don't start with //Pairs:: istream& operator>>(istream& infile, Pairs& p) { char dummy; infile >> dummy >> p.x >> dummy >> p.y >> dummy; return infile; } ostream& operator<<(ostream& outfile, Pairs & p) //Pairs & p keeps it from making another p, //whose destructor will be called, etc... { outfile << '(' << p.x << ',' << p.y << ')'; return outfile; } int main() { int * pInt=0; pInt=new int; //one int on the freestore *pInt=7; cout << "the nameless int is " << *pInt << endl; delete pInt; //doesn't delete the pointer (which is on the stack) //but deletes what the pointer is pointing to //cout << *pInt; //dereferencing a dangling pointer - bad pInt=0; //do this when you delete so you can test it. //cout << *pInt; //dereferencing a null pointer - bad if (pInt!=0) //testing for a null pointer - good cout << *pInt; int arraysize=4; pInt=new int[arraysize]; //Notice you can use a variable for //the array size here. pInt[0]=5; pInt[1]=10; cout << "Good stuff from the freestore: "; cout << setw(5) << pInt[0] << setw(5) <set(5); //use -> for (* ). //who gets the 5, x or y? ans: x, leftmost parameter cout << "partially set pair: " << *pPairs << endl; pPairs->set(10,20); cout << "set pair: " << *pPairs << endl; //We should delete pPairs, but don't. //We are about to get a memory leak. pPairs = new Pairs[3]; //an array of 3 pairs on the freestore cout << "Default values used: \t" << pPairs[0] << '\t' << pPairs[1] << '\t' << pPairs[2] << endl; //which of the above << are Pairs::operator<> pPairs[0] >> pPairs[1] >> pPairs[2]; cout << "The pairs are\n"; int i; for (i=0;i<3;i++) cout << pPairs[i] << endl; delete [ ] pPairs; pPairs=0; pPairs=new Pairs[5]; pPairs[0].set(3,4); pPairs[1].set(9,8); //delete pPairs; //Left out the [ ] //Deletes only pPairs[0]. //Cuts off access to rest of the array, //creating a memory leak - bad. //Will crash some systems. return 0; }