C++ Language



Admission Enquiry Form

  

Constructor in C++ || Default Constructor in C++




What is Constructor?

Constructor is a special function which executes/invoke automatically when we create the object of the class.

It is special member function of the class because it does not have any return type.

Constructor name same as the class name.

Constructor don't have any return type.

Types of Constructor

There are three types of constructor:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor



What is Default Constructor?

Default Constructor is a constructor which does not take any argument or constructor without arguments.

If we don't specify a constructor, C++ compiler automatically generates a default constructor for an object (i.e.implicit default constructor).

Types of Default Constructor

There are two types of default constructor:

  1. Default Constructor created by compiler (implicit constructor)
  2. Default Constructor created by user



Code for Default Constructor in C++.

#include<iostream>
using namespace std;
class Circle // The class
{
float pie; //Data Member
int radius,ar; //Data Members
public: // Access specifier
Circle() //Default constructor
{
pie=3.14;
}
void area() //member Function
{
ar=pie*radius*radius;
cout<<"Area of circle is "<<ar;
}
};
int main()
{
Circle cir; // Object of Circle class (this will call the default constructor automatically)
cir.area();
}

Output:

Area of circle is 803