Destructors

A destructor, sometimes abbreviated as dtor, is a special member function that automates clean-up actions just before an object is destroyed.

When is an object destroyed?

  • When a local (automatic) object goes out of scope (e.g., when a function call returns)
  • When an object created by the new operator is specifically destroyed by the use of the operator delete
  • Just before the program terminates, all objects with static storage are destroyed

The destructor's name is the classname preceded by the tilde (~) character. It has no return type and no parameters, so it cannot be overloaded. If the class definition contains no destructor definition, the compiler will supply one that looks like this:

ClassName::~ClassName()
 { }

We will look at a less trivial example of a destructor in the next section.

When do we need to write a destructor?

In general, a class that directly manages or shares an external resource (opens a file, opens a network connection, creates a process, etc.) needs to free the resource at some appropriate time. Such classes are usually wrappers that are responsible for object cleanup.

Qt's container classes make it easy for us to avoid writing code that directly manages dynamic arrays.

You do not need a destructor if your class:

  • Has simple type members that are not pointers
  • Has class members with properly defined destructors themselves

The default compiler-generated destructor calls the destructors on each of its class members in the order that they are listed in the class definition before the object is destroyed. It does nothing with pointers or simple types.


Part I: Introduction to C++ and Qt 4

C++ Introduction

Classes

Introduction to Qt

Lists

Functions

Inheritance and Polymorphism

Part II: Higher-Level Programming

Libraries

Introduction to Design Patterns

QObject

Generics and Containers

Qt GUI Widgets

Concurrency

Validation and Regular Expressions

Parsing XML

Meta Objects, Properties, and Reflective Programming

More Design Patterns

Models and Views

Qt SQL Classes

Part III: C++ Language Reference

Types and Expressions

Scope and Storage Class

Statements and Control Structures

Memory Access

Chapter Summary

Inheritance in Detail

Miscellaneous Topics

Part IV: Programming Assignments

MP3 Jukebox Assignments

Part V: Appendices

MP3 Jukebox Assignments

Bibliography

MP3 Jukebox Assignments



An Introduction to Design Patterns in C++ with Qt 4
An Introduction to Design Patterns in C++ with Qt 4
ISBN: 0131879057
EAN: 2147483647
Year: 2004
Pages: 268

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net