Saturday, March 1, 2014

Implementing the destructor and finalizer for a class in C++

Destructor:

A destructor is executed when you no longer need an object. To provide a destructor for a class, add a member function that has the same name as the class but is preceded by a tilde character (~).

Finalizer :

Finalizers are called when the garbage collector finally reclaims the object’s memory. You will need a finalizer if you have unmanaged resources, such as pointers to unmanaged classes, file handles, window handles, graphic device contexts, and so on. If you don’t have any of those—and you’ll only tend to do that when you are working with unmanaged code—you probably don’t need a finalizer.

A finalizer is a member function that has the same name as the class but is preceded by an exclamation mark (!).

//MyClass.h Header File
using namespace System;
ref class MyClass
{
String ^name;
public:
MyClass(String ^objectName); // constructor
~MyClass(); // destructor
!MyClass(); // finalizer
void DoSomething(); // 'work' method
};

///MyClass.CPP File

#include "stdafx.h"
using namespace std;
#include "MyClass.h"

MyClass::MyClass(String ^objectName)
{
name = objectName;
Console::WriteLine("Constructor called for {0}", name);
}

MyClass::~MyClass()
{
Console::WriteLine("Destructor called for {0}", name);
}

MyClass::!MyClass()
{
Console::WriteLine("Finalizer called for {0}", name);
}

void MyClass::DoSomething()
{
Console::WriteLine("DoSomething called for {0}", name);
}

//Using the finalizer in Main Program

#include "MyClass.h"
int main(array<System::String^>^ args)
{
MyClass ^m1 = gcnew MyClass("m1");
m1->DoSomething();
Console::WriteLine();
Console::WriteLine("End of program");
Console::WriteLine();
return 0;
}

Output similar to the following appears:

Constructor for m1
DoSomething called
End of Program
Finalizer called for m1




No comments:

Post a Comment