Introduction
In this blog, we will learn about the constructor, types of constructor, and the destructor in C++ language.
What is constructor?
C++ compiler provides a special kind of member function for initialization of objects. This function is called the constructor.
Types of constructor
- Default Constructor
- Parameterized Constructor
- Copy Constructor
Before creating a constructor, always remember the below points.
- Constructor name is same as the class name.
- It is declared with no return types (int, float, double and not even void).
- It is declared in the public section.
- It is invoked automatically when the objects are created.
Default Constructor
A constructor that accepts no parameter is called the default constructor.
Example
- // default constructor example
- #include<iostream.h>
- #include<conio.h>
- class emp
- {
- int id,sal; //member variable
- public:
- emp() //default constructor
- {
- id=1;
- sal=2000;
- }
- void display() // member function for display data
- {
- cout<<"Employee id: "<<id<<endl;
- cout<<"Employee salary: "<<sal<<endl;
- }
- };
- void main()
- {
- emp obj;
- obj.display();
- getch();
- }
Parameterized Constructor
A constructor that takes at least one argument is called parameterized constructor.
Example
- //parameterized constructor
- #include<iostream.h>
- #include<conio.h>
- class emp
- {
- int id,sal; //member variable
- public:
- emp(int empId,int empSal) //parameterized constructor
- {
- id=empId;
- sal=empSal;
- }
- void display() //member function
- {
- cout<<"Employee id: "<<id<<endl;
- cout<<"Employee salary: "<<sal<<endl;
- }
- };
- void main()
- {
- emp obj(1,3000); //passing constructor argument value
- obj.display();
- getch();
- }

Join the conversation! Your thoughts help the community grow.