Home » Learn C++ » Destructors in C++

Destructors in C++

Destructors in C++:

            When an object is destroyed a special member function of that class is executed automatically. This member function is called the destructor function or destructor. The destructor function has the same name as the name of a class but a tilde sign (~) is written before its name. It is executed automatically when an object comes to the end of its life. Like constructors destructors do not return any value. They also do not take any arguments.

For example, a local object is destroyed when all the statements of the function in which it is declared are executed. So at the end of the function, the destructor function is executed. Similarly, global objects (objects that are declared before main function) or static objects arc destroyed at the end of main function. The lifetime of these objects end when the program execution ends. So at the end of program the destructor function is executed. The destructor functions are commonly used to free the memory that was allocated for objects.

 

Passing Objects as Arguments:

            Objects can also be passed as arguments to member functions. When an object is passed as an argument to a member function:

  • Only the name of the object is written in the argument.
  • The number of parameters and their types must be defined in the member function to which the object is to he passed. The objects that are passed are treated local for the member function and are destroyed when the control returns to the calling function.

 

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.