***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Monday, June 14, 2021

DESTRUCTORS

A destructor is also a member function that is automatically invoked. It is also a special member function like constructor.

Constructor constructs the object, whereas the destructor destroys the object.

A destructor deallocates the memory dynamically allocated to the variable(s) or performs other clean up operations.

  • The name of the destructor is also the same as the class name.
  • The destructor’s name is preceded by the tilde symbol „~‟.
  • A destructor is called when an object goes out of scope.
  • A destructor is also declared in the public section.
  • Destructors do not take any argument and hence cannot be overloaded.
  • A destructor does not return any value.
  • A destructor is defined to free (de-allocate) the resources allocated in the program.
  • The address of a destructor cannot be accessed in the program.
  • Constructors and destructors cannot be inherited.
  • A class can have only one destructor.
  • Like constructor, a destructor is also invoked once for each object.

Syntax:-

public:

~classname()

{

-----

}

Example. //demonstrating constructor and destructor

#include<iostream.h>

class sample

{

private:

int x;

public:

sample (int a)

{

x=a;

cout<<"Constructor called for object with value : "<<x<<endl;

}

~sample()

{

cout<<"Destructor called for object with value : "<<x<<endl;

}

};

void main()

{

clrscr();

sample s1(1);

sample s2(2);

sample s3(3);

}

Output:

Constructor called for object with value : 1

Constructor called for object with value : 2

Constructor called for object with value : 3

Destructor called for object with value : 3

Destructor called for object with value : 2

Destructor called for object with value : 1


No comments:

Post a Comment