11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

296Part IV: Inheritancenamespace Schools{char* GraduateStudent::display(){// get description of basic studentchar* pFirst = Student::display();// we’ll add this textchar* pSecond = “-G”;// get a new string and tack second onto firstchar* pName = new char[strlen(pFirst) +strlen(pSecond) + 1];strcpy(pName, pFirst);strcat(pName, pSecond);}}// don’t forget to return the string returned by// Student::display() to the heap before passing// our new string to the callerdelete pFirst;return pName;The GraduateStudent version of display() concatenates a “-G” onto theend of whatever Student returns. It begins by allocating a new characterarray that’s large enough to handle the extra information.Never assume that there’s enough room in the original buffer for any extracharacters to be tacked onto the end.The program copies the contents of the original string into the newly allocatedarray. It then appends the “- G”. The display() function must returnthe buffer allocated by Student::display() to the heap before continuing.Forgetting to return buffers to the heap is known as a memory leak. A programwith memory leaks executes properly at first; however, the programslows more and more as the available memory is lost to the leaks. The programeventually grinds to a halt. Memory leaks are very difficult to find.Implementing an applicationThe two classes, Student and GraduateStudent, have been separated intoindependent source files and included in the Schools namespace. I wrote thefollowing very simple application to invoke the two classes:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!