Constructor in C++

constructor-in-c-plus-plus

constructor in C++ is a special method that is automatically called when an object of a class is created. It is used to initialize the data members of a new object generally. The constructor in C++ has the same name as class or structure.

Types of constructor

  1. Default constructor
  2. Parameterized constructor

What is default constructor ?

A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.

Example of C++ default constructor

#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

What is Parameterized Constructor ?

A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects.

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(101, "Sonoo", 890000); //creating an object of Employee 
    Employee e2=Employee(102, "Nakul", 59000); 
    e1.display();  
    e2.display();  
    return 0;
}

Output:

101  Sonoo  890000
102  Nakul  59000

Advantages of constructor

  • Automatic initialization of objects at the time of their declaration.
  • Multiple ways to initialize objects according to the number of arguments passes while declaration.
  • The objects of the child class can be initialized by the constructors of the base class.

Limitation of constructor

  • A constructor function may not be static
  • Constructor can not be made virtual
  • It can’t be inherited
  • Name of the constructor function must be same as that of the class

0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x