Introduction
In this blog, we will learn about the constructor, types of constructor, and the destructor in C++ language.
Let's start!
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
-
- #include<iostream.h>
- #include<conio.h>
- class emp
- {
- int id,sal;
- public:
- emp()
- {
- id=1;
- sal=2000;
- }
- void display()
- {
- 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
-
-
- #include<iostream.h>
- #include<conio.h>
- class emp
- {
- int id,sal;
- public:
- emp(int empId,int empSal)
- {
- id=empId;
- sal=empSal;
- }
- void display()
- {
- cout<<"Employee id: "<<id<<endl;
- cout<<"Employee salary: "<<sal<<endl;
- }
- };
- void main()
- {
- emp obj(1,3000);
- obj.display();
- getch();
- }
Copy Constructor
A constructor that is used for initializing an object from another object is called copy constructor.
Example
-
-
- #include<iostream.h>
- #include<conio.h>
- class emp
- {
- int id,sal;
- public:
- emp(int empId,int empSal)
- {
- id=empId;
- sal=empSal;
- }
- emp(emp &em)
- {
- id=em.id;
- sal=em.sal;
- }
- void display()
- {
- cout<<"\nEmployee id: "<<id<<endl;
- cout<<"Employee salary: "<<sal<<endl;
- }
- };
-
- void main()
- {
- emp obj(1,2000);
- emp obj1(obj);
-
- obj.display();
- obj1.display();
- getch();
- }
What is destructor?
A destructor is used for destroying the objects that have been created by the constructor.
Before creating a destructor, always remember the below points.
- Destructor name is same as the class name and is prefixed with tilde (~).
- It can neither return a value nor can it take any parameter.
Example
-
-
- #include<iostream.h>
- #include<conio.h>
- class emp
- {
- int id,sal;
- public:
- emp()
- {
- id=1;
- sal=5000;
- }
- ~emp()
- {
- cout<<"Ok Bye for now...";
- }
- void display()
- {
- cout<<"Employee id: "<<id<<endl;
- cout<<"Employee salary: "<<sal<<endl;
- }
- };
- void main()
- {
- emp obj;
- obj.display();
- getch();
- }
Summary
In this blog, I covered constructor, constructor types, and destructor in C++ language. If you face any problem, please comment. Thanks for reading.