// showing how to pass and return pointers to objects // as well as arrays of object pointers // RPF 2/8/01 -- for COM1101, Labs 5 & 6 #include using namespace std; // c is a trivial class with one member variable class c { public: int n; }; void passPtr(c *cArg); // prototype, argument is pointer to a c void passPtr(c *cArg) {} // definition with empty body void passPtrArr(c *cArrArg[]); // prototype, argument is array of pointers to c void passPtrArr(c *cArrArg[]){} // definition with empty body c* returnPtr(c *cArrArg[]); // prototype, returns ptr to one c object c* returnPtr(c *cArrArg[]){ cArrArg[2]->n = 55; // sets member var n of 2nd element to 55 return cArrArg[2]; // returns value of the array el. 2 which is a pointer } void changeAnObj(c *cObjPtr); // pass an object via pointer and change it // The pointer is passed and a value within the object is changed. // When the function is finished, the object pointed to has been changed // internally, even though the pointer hasn't -- the object is still at // the same region in memory. Just one of the values stored in that region // has been changed. void changeAnObj(c *cObjPtr) { cObjPtr->n += 11; } void main() { c *cPtr; cPtr = new c; passPtr(cPtr); c *cPtrArr[10]; cPtrArr[2] = new c; passPtrArr(cPtrArr); // called with entire array passPtr(cPtrArr[4]); // called with one element (also a pointer) // fn. returnPtr() is given the entire array, sets the member var n // of the second item in the array (pointer to a c created with new) // It returns only a pointer to that one element and the n val from // that one c is printed. cout << "member n for 2nd element is: " << returnPtr(cPtrArr)->n << endl; c *anotherC = new c; anotherC->n = 14; cout << "before entering fn. n is: " << anotherC->n << endl; changeAnObj(anotherC); cout << "and after returning, n is: " << anotherC->n << endl; char k; cin >> k; // to pause, if necessary } // main()