Constructor in C++ is a specific method in C++ that is called automatically when an object is created. In general, it’s used to set up the data members of a new object. In C++, the constructor name is the same as a class or structure.
In C++, there are two types of constructors.
- Default constructor
- Parameterized constructor
C++ Default Constructor:
The default constructor is a function that has no argument. It is called at the time of Object creation.
Let’s look at a basic C++ default Constructor example.
#include <iostream> using namespace std; class Employee { public: Employee() { cout<<"Default Constructor Invoked"<<endl; } }; int main(void) { Employee e1; //creating an object of Employee Employee e2; return 0; }
Output:
Default Constructor Invoked
Default Constructor Invoked
C++ Parameterized Constructor:
A constructor is called a parameterized constructor which has parameters or arguments. It helps to provide different values according to different objects creation.
Let’s see an example of Parameterized constructor:
#include <iostream> using namespace std; class Employee { public: int id;//data member (also instance variable) string name;//data member(also instance variable) float salary; Employee(int i, string n, float s) { id = i; name = n; salary = s; } void display() { cout<<id<<" "<<name<<" "<<salary<<endl; } }; int main(void) { Employee e1 =Employee(501, "Lingaraj", 750000); //creating an object of Employee Employee e2=Employee(502, "Senapati", 80000); e1.display(); e2.display(); return 0; }
Output:
501 Lingaraj 750000
502 Senapati 80000