Destructors (new & delete operators)

The destructor fulfills the opposite functionality of constructors. It is automatically called when an object is destroyed, either because its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or because it is an object dynamically assigned and it is released using the operator delete. The destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also return no value.

The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed we want to release the memory that the object was allocated.

Example 1

// example on destructors
#include <iostream>
using namespace std;

class CRectangle {
    int *width, *height;
  public:
    CRectangle (int,int);
    ~CRectangle ();
    int area () {return (*width * *height);}
};

CRectangle::CRectangle (int a, int b) {
  width = new int;  // -------- 1
  height = new int; // -------- 2
  *width = a;
  *height = b;
}

CRectangle::~CRectangle () {
  delete width;   // -------- 3
  delete height;  // -------- 4
}

int main () {
  CRectangle rect (3,4), rectb (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  return 0;
}

The new Operator (1 & 2)

C++ provides a different approach to obtaining blocks of memory: the new operator. This versatile operator obtains memory from operating system and returns a pointer to its starting point.

   width = new int;  // -------- 1
   height = new int; // -------- 2

The delete Operator (3 & 4)

If your program reserves many chunks of memory using new, eventually all the available memory will be reserved and the system will crash. To ensure safe and efficient use of memory, the new operator is matched by a corresponding delete operator that returns memory to the operating system.

   delete width;   // -------- 3
   delete height;   // -------- 4

Deleting the memory does not delete the pointer that points to that memory (width and height in this example), and doesn’t change the address value in the pointer. However, this address is no longer valid; the memory it points to may be changed to something entirely different. Be careful that you don’t use pointers to memory that has been deleted.

Static Class Data

Static data members of a class are also known as “class variables”, because there is only one unique value for all the objects of that same class. Their content is not different from one object of this class to another. For example, it may be used for a variable within a class that can contain a counter with the number of objects of that class that have been created, as in the following example:

Example 2

// static members in classes
#include <iostream>
using namespace std;

class CDummy
{
  public:
    static int n;
    CDummy ()
    {         n++;     }
~CDummy()
    {    n--;  }
};

int CDummy::n=0; // initialization of static variable 'n', only once

int main ()
{
  CDummy a;
  cout <<" The value of static variable is: " << a.n << endl;

  CDummy b[5];
  cout << " The value of static variable is: " << CDummy::n << endl;

 CDummy * c = new CDummy;

 cout << a.n << endl;
 delete c;
 cout << CDummy::n << endl;

  getchar();
  return 0;
}

In fact, static members have the same properties as global variables but they enjoy class scope. For that reason, and to avoid them to be declared several times, we can only include the prototype (its declaration) in the class declaration but not its definition (its initialization). In order to initialize a static data-member we must include a formal definition outside the class, in the global scope, as in the previous example:

 Int CDummy::n=0;

Because it is a unique variable value for all the objects of the same class, it can be referred to as a member of any object of that class or even directly by the class name (of course this is only valid for static members):

cout << a.n;
cout << CDummy::n;

These two calls included in the previous example are referring to the same variable: the static variable ‘n’ within class CDummy shared by all objects of this class.

Once again, it is reminded that in fact it is a global variable. The only difference is its name and possible access restrictions outside its class.

Acknowledgement:

Most of the contents above have been taken directly from here solely for the purpose of education.

Exercise

1. In ocean navigation, locations are measured in degrees and minutes of longitude(east or west from Greenwich) and as well as latitude(north or south from the equator). Create a class angle that includes three data member variables: an int for degrees, a float for minutes, and a char pointer (which will point to dynamically allocated memory through the constructor, and will be used to de-allocate memory through the destructor) for the direction (North, South, East, or West). This class can hold either a latitude variable or a longitude variable, not both longitude and latitude, simultaneously, to represent the location. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initializers are provided. Write one member function to obtain an angle value (in degrees and minutes) and a direction from the user, another member function should display the angle value in 179:59.9-East format.

2. Create a class called ship that incorporates a ship’s auto generated serial number and location for each ship created from the class. That is the first ship object created will be numbered 1 and its particular position, the second one will be numbered 2 and its particular position, and so on. Use two objects of the angle class, as data members, from the previous exercise to represent the ship’s latitude and longitude. A member function of the ship class should get position from the user and store it in the object; another should report the serial number and position. Write a main() program that creates three ships, asks the user to input the position of each, and then displays each ship’s number and position.

Hint:

 a- To generate auto generated serial number, you will need another data member that records a count of how many objects have been created so far (i.e. the static data member). Then, as each object is created, its constructor can examine this count member variable to determine the appropriate serial number for the new object. 

b- Use two objects of angle in the ship class as data members; likewise, variables of int are used in the class as data members. For example,

class
{          
int a;
int b;
};

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.