What is constructor and destructor in c++ ? Is every constructor is default constructor? Is it necessary to use destructor with constructor and what is their return type?
Use of constructor in c++.
Constructor:
Main use is to initialize objects. Initialization is carried out by the special member function of a constructor.
-It takes same name as the class.
-It must be declared 'public' member.
-Overloading is possible.
Destructor:
Destructors have the opposite function of a constructor. The main use is to release dynamic allocated memory.
-Destructor has the same name as class but (~) sign preceding it.
-They do not take any arguments, which mean they cannot be overloaded.
-Destructor must also be defined as public.
-No return type is specified.
Use of constructor in c++.
Constructor, as the name suggest is to construct something. We construct something as much we require. In context of computer with C++, C++ uses memory of computer.
In our program we create variables,functions and so on. We need to create these as our requirements. The main function of constructor is to create no of objects required in our program.Â
Â
Constructors and Destructors both are functions and they provide efficiency and flexibility in the program.
Â
Like if we want to assign values to the data members of the class, we use function for this. For example we have a member function getdata of the class test.
Â
void getdata(int a,int b)
{
x=a;
y=b;
}
Â
To call this function in the main program we will create an object and then that object will call this function like this.
Â
test ob1;
ob1.getdata(10,15);
Â
These two statements will assign the values to data members x and y. In place of this we can use a constructor.
Â
test(int a,int b)
{
x=a;
y=b;
}
Â
We will call this constructor in the main program like this.
Â
test ob1(10,15);
Â
With a single statement object is being created and values are also being assigned to the data members. Always remember constructor has the same name as the class name and is automatically called when objects are created.
Â
And before talking about the destructor, you should know that C++ is a block oriented language also. Block means the braces {….}. So the destructor is always automatically called where the block is closed i. e. closing brace.
Here is a diagram for you.
Â
Â
Destructor also has the same name as the class name but is preceded by a tilde. We use constructor after the opening brace { and destructor is automatically called and destroy the members created by constructor in that block.Â
Â
Every constructor is not a default constructor. This is not necessary to use destructor with constructor. Constructor and Destructor both do not have any return type.