C++ 44: Dynamic Constructors and Destructors

 Dynamic Constructor

The dynamic constructor which runtime reserves the memory for the data memebers of the class is called as dynamic constructor.

Destructors / Deconstructors 

  • The destructors are a special type of function in a class which is automatically involved just before the object is going to destroy.
  • The destructors is used to truncate the object. That means to relese all the resources hold by object just before the object is going to destroy.

Characteristics of destructors

  • Destructors have same name as the class name with tilde(~)operator preceded.
  • Destructor is automatically called just before object is going to destroyed
  • Destructors cannot  have any return_type. Hence cannot return value.
  • Destructor cannot accept any arguments hence not possible to overload.
  • Destructors cannot inherit in derived class
  • In case of derived classes the destructors invoke excatly reverse order in which class is created.
  • Destructors is used to release the resources (memory resources) hold by the object before the object is going to destroy.

NOTE:
A destructor is called automatically in following cases:
  1. When the function containing local object ends.
  2. When a block containing local object ends.
  3. When delete object is used.
Example:
#include <iostream>
#include <string.h>
using namespace std;

class MyString
{
private:
    char *N;

public:
    MyString(char n[])
    {
        int length = strlen(n);
        N = new char[length + 1]; //Reserving memory Dynamically
        strcpy(N, n);
    }
    void showData()
    {
        cout << "String = " << N << endl;
    }
    ~MyString()
    {
        delete N;
        cout << "Destructor Invoked!" << endl;
    }
};

int main()
{
    MyString *p = new MyString("Jack");
    p->showData();

    return 0;
}

Output:

String = Jack
Destructor Invoked!


 




Comments

Popular posts from this blog

C++ 38: Visibility Modes Public, Private and Protected