Saturday, 4 June 2016

Constructors And Destructor In C++


The automatic initialization as soon as the object is created is called as constructor.
We should know the concept of access specifiers here. Whenever we create a class, we put variables under public, private, protected etc.
Now the variables which comes under the Private are known as Member Variables while the variables which comes under the Private section are known as Member Function. The Constructors are always declared in the public section of the program. The prime work of the constructor is to initialize Member Variable from the PRIVATE class.
The constructor has the same name as the class name.
Destructor is the anti of Constructor. If object is born when constructor is created, it dies when destructor is called. Destructor has also the same name as the class name except for a trend that it is preceded by ~ symbol.
Program:
#include<iostream.h>
#include<conio.h>
class ratio
{
private:
int num,den;
public: \\Access specifier
ratio() \\Constructor
{
cout<<“Object is born\n\n”;
}
~ratio() \\Destructor
{
cout<<“Object dies\n\n”;
}
};
void main()
{
clrscr();
{
ratio x; \\This is how object is created i.e Class name then Object name.
Also constructor is called here because object is created here(See the text above)
cout<<“Now x is alive\n\n”;
}
cout<<“Now between the blocks\n\n”; \\you need to be careful with blocks. Blocks are nothing but the curly brackets inside which the program is written.
{
ratio y; \\Another object created. Again the constructor will be called 
cout<<“Now y is alive\n\n”;
}
getch();
}

No comments:

Post a Comment