C++ - Constructors


Advertisements

Previous Page Next Page

A constructor is a special member function of a class which automatically executed when a new object of the class is created. It allows the class to initialize member variables and allocate memory.

The constructor function is declared just like a regular member function except the class name and function name should be same without any return type.

Example:

In the below example, a class called Circle is created. A constructor is also created which is used to initialize the member variable called radius of the same class.

#include <iostream>
using namespace std;
 
class Circle
 {
   public:
     int radius;
     float area()
     {
        return 22/7.0*radius*radius;
     }
     Circle(int);
 };

Circle::Circle(int x)
 {
   radius = x;
 }

int main (){
    Circle Circle_1(5);
    Circle Circle_2(10);

    cout<<Circle_1.area()<<"\n";
    cout<<Circle_2.area()<<"\n"; 
    return 0;
}

Output

78.57
314.3

Constructor Overloading

Like functions, a constructors can also be overloaded in C++. With constructor overloading feature in C++, two or more constructors can be created in the same class with different definitions: different number of parameters and/or different types of parameters. The compiler automatically calls the constructor which matches the argument passed while creating the object.

Example:

In the below example, two objects of class Circle are created: Circle_1 and Circle_2. Circle_1 is created without any argument and Circle_2 is created with one argument.

#include <iostream>
using namespace std;
 
class Circle
 {
   public:
     int radius;
     float area()
     {
        return 22/7.0*radius*radius;
     }
     Circle();
     Circle(int);
 };

Circle::Circle()
 {
   radius = 1;
 }

Circle::Circle(int x)
 {
   radius = x;
 }

int main (){
    //syntax for calling default constructor
    Circle Circle_1;

    Circle Circle_2(10);

    cout<<Circle_1.area()<<"\n";
    cout<<Circle_2.area()<<"\n"; 
    return 0;
}

Output

3.143
314.3

In this example two constructors are created. The first constructor (default constructor) takes no parameters and the second constructor takes one parameter to initialize an object of the class Circle. A constructor is called default constructor, if it takes no arguments to initialize the object. Please note down the syntax to initialize an object using default constructor in the above example.


Previous Page Next Page