Explain Default Constructor with Example and Program, Destructors with Examples and Syntax
Default constructor:
class sample
{ int a, b;
public:
sample()
{ a=0;b=0;
}
void show()
{ cout<<a<<b;
}
};
void main()
{ sample s;
s.show();
}
Destructors :-
1. It’s a special function which has the same name as that of the Class name.
2. It has No Input-Arguments and No Return-Type, not even void.
3. Its definition is preceded by Tild symbol “ ~ “.
4. Its called implicitly as soon as the scope for any object finishes. Its invoked for every object .
5. The compiler creates a Destructor for every Class implicitly by default.
6. If a Destructor is explicitly defined then the compiler will always use the explicitly defined Destructor.
7. Its generally used to free up the spaces allocated by using “ new “ operator during calling of Constructors. The de-allocation should be done using “ delete “ operator
8. The object that is created First is Destructed Last and object created Last is Destructed First.
9. Syntax :- ~class-name ( ) { code }
1. Example :-
Write a program to count the number of Objects created and destroyed using constructor and destructor functions. The objects should be identified by a unique ID, which should be mentioned while creation and destruction of the object.
class sample
{
static int count;
int a;
public:
sample() //Constructor
{
a=++count
cout<<"\n"<<" Object number = "<<a<<” is created”;
}
~sample() //Destructor
{
cout<<"\nObject number = "<<a<<”is destroyed”;
}
};
int sample::count;
void main()
{ clrscr();
{
sample ob1; //Created First Destructed Last
sample ob2; //Created Second Destructed Last Second
sample ob3; //Created Last Destructed First
} //As scope is finishing so Destructors would be called
getch();
}
Labels: C++