C++ Constructors

A constructor in C++ is a special method that is automatically called when an object of a class is created.

To create a constructor, use the same name as the class, followed by parentheses ():

Example:-

#include<iostream.h>
#include<conio.h>
class aptech
{
public:
aptech()
{
cout<<"Hello constructor";
}
};
void main()
{
aptech ap;
clrscr();
getch();
}

Types of Constructor in C++

There can be three types of constructors in C++.
  • Default constructor
  • Parameterized constructor
  • Copy Constructor

C++ Default Constructor

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

C++ Parameterized Constructor

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

Example:-

#include<iostream.h>
#include<conio.h>
class aptech
{
public:
aptech(int a)
{
cout<<a;
}
};
void main()
{
aptech ap(2);
clrscr();
getch();
}

C++ Copy Constructor

A member function known as a copy constructor initializes an item using another object from the same class-an in-depth discussion on Copy Constructors.

Example:-

#include<iostream.h>
#include<conio.h>
class aptech
{
public:
aptech()
{
cout<<"Hello constructor";
}
};
void main()
{
aptech ap;
aptech ap1=ap;
clrscr();
getch();
}

Destructors in C++

Destructor is an instance member function that is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed.destructor is declared with tiled (~) sign.

Example:-

#include<iostream.h>
#include<conio.h>
class aptech
{
public:
aptech()
{
cout<<"Constructor";
}
~aptech()
{
cout<<"Destructor";
}
};
void main()
{
aptech ap;
clrscr();
getch();
}