C++ Constructor and Destructor
In OOPS constructor and destructor play very vital role , Now if we deal them as common English words ,Constructor means to construct something and destructor means to destroy something.
Constructor
Inside a class we cannot assign values to variables directly for that we made a constructor ,
Now question is how to made a constructor ? So,what we have to do is write the name of a class and put round bracket i.e after the name just like functions and then made its body and the variables will be assigned values inside the body of constructor.Every class have a constructor whether you declare it or not and its know as default constructor remember constructor have several types and is a very detailed topic but as we are dealing with the basic constructor and its function so we won't be going in details ,whenever you are going to declare an object of this class in main body for each and every object there will be constructor called separately i.e if we have three objects of same class constructor will be called three times Although direct assigning of values work in some compilers but according to standard rules you have to make constructor for assigning the values to Datatypes ,Let's explain it through an example for making it further clear
Now question is how to made a constructor ? So,what we have to do is write the name of a class and put round bracket i.e after the name just like functions and then made its body and the variables will be assigned values inside the body of constructor.Every class have a constructor whether you declare it or not and its know as default constructor remember constructor have several types and is a very detailed topic but as we are dealing with the basic constructor and its function so we won't be going in details ,whenever you are going to declare an object of this class in main body for each and every object there will be constructor called separately i.e if we have three objects of same class constructor will be called three times Although direct assigning of values work in some compilers but according to standard rules you have to make constructor for assigning the values to Datatypes ,Let's explain it through an example for making it further clear
Destructor
As the name suggest Dtor(Destructor) is use to destroy the object it is automatically invoked so its mean it also present by default but programmer can also handle it in a way that he want to display some message before the program ends he can write it in Dtor now how to make Dtor? The process of making Dtor is almost the same as that of Constructor, we will write the name of the class in class body and will put round bracket i.e () in the end and then will made its body only one thing will be included i.e "~ " this is known as tilde and which will be place it in the start of the Dtor declaration statement in code,Now to make it further clear lets explain it through an example
0 comments:
Post a Comment