11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 16: “Why Do You Build Me Up, Just to Tear Me Down, Baby?” 217Dissecting a DestructorJust as objects are created, so are they destroyed (ashes to ashes, dust todust). If a class can have a constructor to set things up, it should also have aspecial member function to take the object apart. This member is called thedestructor.Why you need the destructorA class may allocate resources in the constructor; these resources need to bedeallocated before the object ceases to exist. For example, if the constructoropens a file, the file needs to be closed before leaving that class or the program.Or, if the constructor allocates memory from the heap, this memorymust be freed before the object goes away. The destructor allows the class todo these cleanup tasks automatically without relying on the application tocall the proper member functions.Working with destructorsThe destructor member has the same name as the class, but with a tilde (~)added at the front. (C++ is being cute again — the tilde is the symbol for thelogical NOT operator. Get it? A destructor is a “not constructor.” Très clever.)Like a constructor, the destructor has no return type. For example, the classStudent with a destructor added appears as follows:class Student{public:Student(){semesterHours = 0;gpa = 0.0;}~Student(){// ...whatever assets are returned here...}protected:int semesterHours;float gpa;};

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

Saved successfully!

Ooh no, something went wrong!