destructor in c++ with example

(2) Why destructors in c++?
Answer:
Goal of c++ is to create such type of class which is very similar to basic data type like int char, float etc. Each basic data type in c++ has one of the storage class (auto, register, static and extern) on the basis of storage class each data member has different scope and visibility. For example auto variable has scope and visibility within block i.e. when control come out from block memory is deallocated and variable is destroyed.
Example:
#include<stdio.h>
#include<iostream.h>
int a=10;
int main()
{ //block1
clrscr();
int a=5; //scope within block1
int b=15; //scope within block1
cout<<"a="<<a<<"b="<<b;
{ //block2
int b=20; //scope within block2
int c=30; //scope within block2
cout<<"b="<<b<"c="<<c;
}
cout<<"a="<<a<<"b="<<b;
getch();
return 0;
}
Output:
a=5 b=15
b=20 c=30
a=5 b=15
But with concept of only member function, friend function and constructor we cannot achieve this goal.

No comments: