Home >>C++ Tutorial >C++ Constructor

C++ Constructor

C++ Constructor

Just at the time of the creation of an object a special method that is invoked automatically is known as the constructor in C++. The general use of the constructor lies in initializing the new object's data members and it generally has the same name as the class or the structure.

There are two types of known constructor in C++.

  • Default constructor
  • Parameterized constructor

1. C++ Default Constructor

The constructor that is generally invoked at the creation of an object and contains nil arguments is known as the default constructor in C++.

Here is an example of the same:

#include <iostream>  
using namespace std;  
class Student  
 {  
   public:  
        Student()    
        {    
            cout<<"This is Default Constructor of C++"<<endl;    
        }    
};  
int main(void)   
{  
    Student stu1; //creating Object of Student class   
    Student stu2;
	Student stu3;	
    return 0;  
}  
Output :
This is Default Constructor of C++
This is Default Constructor of C++
This is Default Constructor of C++

2. C++ Parameterized Constructor

Parameterized Constructor's meaning lies its name as it the constructor in C++ that has got some parameters and its general use is to deliver different values to the distinct objects.

Here is an example of the Parameterized Constructor in C++:

#include <iostream>
using namespace std;
class Student {
   public:
       int roll; 
       string name;
       Student(int x, string y)  
        {  
            roll = x;  
            name = y;  
        }  
       void show()  
        {  
            cout<<roll<<"  "<<name<<"  "<<endl;  
        }  
};
int main(void) {
    Student stu1 =Student(100, "Anand");
    Student stu2=Student(101, "Shipra"); 
    stu1.show();  
    stu2.show();  
    return 0;
}
Output :
100 Anand
101 Shipra

No Sidebar ads