What is a Constructor…???It is a method which have it’s name same as it’s respective class name.In this tutorial we shall learn about constructors in detail.
The main properties of constructors are:
1.Name of the constructor is same as class name.
2.They don’t have any return type….even void too.
3.Constructor are invoked implicitly whenever an object is created.
They are two types of constructors in C++.
1.default constructor.
2.parameterized constructor.
A constructor which do not have any parameters is called as default constructor.
A constructor which takes one or more parameters is called as parameterized constructor.
Let us write a simple code to demonstrate the use of constructors in programming.
#include<iostream.h> #include<conio.h> class cont_demo { public: cont_demo(); //default constructor cont_demo(int ); //parameterized constructor } cont_demo :: cont_demo() { cout<<"\n\n\t\t *****DEFAULT CONSTRUCTOR IS INVOKED*****"; } cont_demo :: cont_demo(int i) { cout<<"\n\n\t\t*****PARAMETERIZED CONSTRUCTOR IS INVOKED*****"; } void main() { clrscr(); cont_demo ob; cont_demo ob1(1); getch(); }
But the above program is also an example of method overloading…i.e using the same name for two or more methods with a difference in number of parameters.
OUTPUT:
You can download the program:download