Presentation is loading. Please wait.

Presentation is loading. Please wait.

Destructors.

Similar presentations


Presentation on theme: "Destructors."— Presentation transcript:

1 Destructors

2 Purpose of Destructors
To take care of any "clean up" needed when an object of the class is deallocated. Destructors are normally needed for objects with dynamically allocated memory to prevent creation of garbage.

3 Invocation of Destructors
Destructors are automatically invoked when an object is deallocated, whether allocated automatically or dynamically.

4 Syntax The same as constructors, except a tilde ~ is added to the front class thing() { public: thing(); // constructor ~thing(); // destructor };

5 Syntax thing::thing() { // constructor cout << "Construct!\n"; } thing::~thing() { // destructor cout << "Destruct!\n";

6 Semantics Example void fun() { thing x; cout << "Have fun!\n"; } void main() { fun(); cout << "Done\n";

7 Semantics Example void fun() { thing x; // constr invoked cout << "Have fun!\n"; } void main() { fun(); cout << "Done\n";

8 Semantics Example thing::thing() { // constructor cout << "Construct!\n"; } thing::~thing() { // destructor cout << "Destruct!\n";

9 Semantics Example void fun() { thing x; cout << "Have fun!\n"; } void main() { fun(); cout << "Done\n";

10 Semantics Example void fun() { thing x; cout << "Have fun!\n"; } // destructor invoked! void main() { fun(); cout << "Done\n"; }

11 Semantics Example thing::thing() { // constructor cout << "Construct!\n"; } thing::~thing() { // destructor cout << "Destruct!\n";

12 Semantics Example void fun() { thing x; cout << "Have fun!\n"; } void main() { fun(); cout << "Done\n";

13 Semantics Example 2 void main() { thing * p = NULL; p = new thing; cout << "Hello\n"; delete p; cout << "Bye\n"; }

14 Semantics Example 2 void main() { thing * p = NULL; p = new thing;//constr invoked cout << "Hello\n"; delete p; cout << "Bye\n"; }

15 Semantics Example 2 void main() { thing * p = NULL; p = new thing; cout << "Hello\n"; delete p; cout << "Bye\n"; }

16 Semantics Example 2 void main() { thing * p = NULL; p = new thing; cout << "Hello\n"; delete p; //dest invoked cout << "Bye\n"; }

17 Semantics Example 2 void main() { thing * p = NULL; p = new thing; cout << "Hello\n"; delete p; cout << "Bye\n"; }

18 Typical Use For every pointer in an object, delete it IF it is not NULL. thing::~thing() { if (next != NULL) delete next; }

19 Vocabulary Term Definition Destructor
Special method of a class that is automatically invoked when an object of the class is deallocated. It's name is the same as the class name preceded by a tilde and having no return type or arguments.


Download ppt "Destructors."

Similar presentations


Ads by Google