Home

Destructors

 

Introduction

As opposed to a constructor, a destructor is called when a program has finished using an object. A destructor does the cleaning behind the scenes. Like the default constructor, the compiler always creates a default destructor if you don't create one. Unlike the constructor, the destructor cannot be overloaded. This means that, if you decide to create a destructor, you can have only one. Like the default constructor, a destructor also has the same name as its class. This time, the name of the destructor starts with a tilde.

To create a destructor, type ~ followed by the name of the class. Here is an example:

public ref class CFlower
{
public:
    String ^ Type;
    String ^ Color;
    String ^ Arrangement;
    double   UnitPrice;

    CFlower() : Type(L"Roses"), Color(L"Red"),
	        Arrangement(L"Basket"), UnitPrice(35.95)
    {
    }

    CFlower(String ^ type);
    CFlower(String ^ type, String ^ color,
		    String ^ argn, double price);
    CFlower(const CFlower ^ &copier);
    ~CFlower();
};
 

Practical LearningPractical Learning: Creating a Destructor

  1. Access the StoreItem.h header file
  2. To create a destructor, add the following method:
     
    #pragma once
    using namespace System;
    
    namespace ElectronicsStore
    {
        public ref class CStoreItem
        {
        public:
            // An item whose characteristics are not (yet) known
            CStoreItem(void);
            // An item that is known by its make, model, and unit price
            CStoreItem(long itmNbr, String ^ make,
    			String ^ model, double unitPrice);
            // An item that is known by its name and unit price
            CStoreItem(long itmNbr, String ^ name, double unitPrice);
            // An item completely defined
            CStoreItem(long itmNbr, __wchar_t category,
    	           String ^ make, String ^ model,
    		   double discountRate, double unitPrice);
            ~CStoreItem();
    
        private:
            . . . No Change
        };
    }
  3. Access the StoreITem.cpp source file and add the destructor as follows:
     
    #include "StoreItem.h"
    using namespace System;
    
    namespace ElectronicsStore
    {
        . . . No Change
        
        CStoreItem::CStoreItem(long itmNbr, __wchar_t category,
    			   String ^ make, String ^ model,
    			   double discountRate, double unitPrice)
    	   : nbr(itmNbr),
    	     cat(category),
    	     mk(make),
    	     mdl(model),
    	     discount(discountRate),
    	     price(unitPrice)
        {
        }
    
        CStoreItem::~CStoreItem()
        {
    	
        }
    
        . . . No Change
    }
  4. Execute the application to test it
  5. Close the DOS window

Object Destruction in the Native Heap

As done with a default constructor, you may not need to do anything in the implementation of a destructor. In fact, when a program terminates, the compiler can itself destroy all of the objects and variables that your program had used. However, if you dynamically create some variable in the constructor(s), using pointers, you can then delete or destroy them in the destructor. If the variables were created as regular pointers, you can use the delete operator.

Object Destruction and the Managed Heap

In C++/CLI, if you create a handle, the compiler would take care of destroying it when the program terminates. This is the role of the garbage collector. It determines when the object is not needed anymore instead of you taking care of it. Still, if you want, you can create a handle in a constructor and destroy it the destructor, using the delete operator. Here is an example:

Header File: Circle.h
#pragma once

namespace Geometry
{
    public ref class CCircle
    {
	public:
        CCircle();
        ~CCircle();

        double ^ Radius;
        double Area();

        literal double Pi = 3.14159;
    };
}
Source File: Circle.cpp
#include "circle.h"

namespace Geometry
{
    CCircle::CCircle()
    {
        Radius = gcnew double(0.00);
    }

    CCircle::~CCircle()
    {
        delete Radius;
    }

    double CCircle::Area()
    {
	return *Radius * *Radius * Pi;
    }
}
Source File: Exercise.cpp
#include "Circle.h"

using namespace System;
using namespace Geometry;

CCircle ^ CreateCircle()
{
    Console::Write(L"Enter the radius of the circle: ");
    double ^ rad = double::Parse(Console::ReadLine());

    CCircle ^ circle = gcnew CCircle();
    circle->Radius   = rad;

    return circle;
}

void DescribeCircle(CCircle ^ round)
{
    Console::WriteLine(L"Circle Description");
    Console::WriteLine(L"Radius: {0:F}", round->Radius);
    Console::WriteLine(L"Area:   {0:F}", round->Area());
}

int main()
{
    CCircle ^ figure = CreateCircle();
    Console::WriteLine();
    DescribeCircle(figure);

    Console::WriteLine();

    return 0;
}

 Here is an example of running the program:

Enter the radius of the circle: 48.12

Circle Description
Radius: 48.12
Area:   7274.46

Press any key to continue . . .

 

 

Previous Copyright © 2006 FunctionX, Inc. Next