A Constructor is a function with the same name as the class.
class Heyconstructor{
Heyconstructor(){ //Constructor
//statements
}
}
In the above snippet Heyconstructor() is a constructor which has the same name as the class.
Every time if any object of above class is created, the constructor is by default called.
A constructor is used to provide initial values to the class fields when an object is created.
Every class has a constructor.
If we don’t write a constructor then the compiler writes one for us.
The constructor that C++ compiler writes for us is known as Default constructor.
But, if we write a constructor the default constructor is never created.
Just like any other function, a constructor may or may not have any parameters.
If a constructor has parameters it is known as a parametrized constructor.
A default constructor has no parameters.
Constructors in action
Let’s begin by writing a simple constructor.
class Heyconstructor{
public:
Heyconstructor(){
cout<<“Hi! I am a constructor“;
}
};
We have written a simple constructor which prints “Hi! I am a constructor” every time a new object is created.
class Heyconstructor{
public:
Heyconstructor(){
cout<<“Hi! I am a constructor“;
}
};
int main() {
Heyconstructor hi;
}
We have created a new object. The above program on execution gives the output.
Hi! I am a constructor
We saw how a constructor without parameters works.
Now let’s see how we can assign initial values to the class members.
For this, we will use a Parameterized constructor.
class Heyconstructor{
public:
int num;
Heyconstructor(int n){
num = n;
cout<<“Hi! For the “<<num<<“ time.“;
}
};
Awesome, we have a constructor Heyconstructor having one parameter which is of type integer.
Let’s create an object of type Heyconstructor and pass some value as this time we have a parameterized constructor.
class Heyconstructor{
public:
int num;
Heyconstructor(int n){
num = n;
cout<<“Hi! For the “<<num<<“ time.“;
}
};
int main() {
Heyconstructor hi(100);
}
Can you try to guess the output of the above snippet?
We are passing 100 while creating the new object hi.
In the constructor we are initializing num with the value of n.
So, the output will be:
Hi! For the 100 time.
Now we know how to write constructors and also how to use them.
You have to. 😛
To Summarize
- A Constructor is a function with the same name as the class.
- If we do not write a constructor then C++ compiler writes one for us which is known as default constructor.
- whenever a new object is created then the constructor is called.
- A constructor is used to provide initial values to the class members when an object is created.
- If a constructor has parameters it is known as a parameterized constructor.
- The constructor that C++ compiler writes for us is known as Default constructor.
- The number of times constructer called is equal to the number of times new objects created.