Loading...
C++ Constructors

C++ Constructors

In this tutorial, we will learn about the C++ constructor and its type (default, parameterized, and copy-constructor) with the help examples.

Constructor

A Constructor is a special member method which will be called implicitly (automatically) whenever an object of class is created.
Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created.
Constructors initialize values to object members after storage is allocated to the object.


How constructors are different from a normal member function?

A constructor is different from normal functions in following ways: 

  • Constructor has same name as the class itself.
  • Constructors don’t have return type.
  • A constructor is automatically called when an object is created.
  • If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).

For example,

class  A {
   public:

    // constructor
    A() {
        // object initialization
    }
};

Here, the function A() is a constructor of the class A. Notice that the constructor

  • has the same name as the class,
  • does not have a return type, and
  • is public

C++ Types of Constructors

Constructors are of three types:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor


C++ Default Constructor

Default constructor is the constructor which doesn't take any argument. It has no parameter. It is invoked at the time of creating object.

For example:-


Example 1: C++ program to demonstrate the use of Default Constructor

#include <iostream>
using namespace std;

// declare a class
class Cube {

  private:
       int side;

   public:
    // create a constructor
    Cube() {

        // initialize private variables
        side = 6;

        cout << "How many sides in a 3/3 cube." << endl;
        cout << "Cude has"  << side << "Sides." endl;
    }
};

int main() {

    // create an object
    Cube cude1;

    return 0;
}

Output

How many sides in a 3/3 cube.
Cube has 6 Sides.

Here, when the cube1 object is created, the Cube() constructor is called. This sets the side variable of the object to 6.

Note: If we have not defined a constructor in our class, then the C++ compiler will automatically create a default constructor with an empty code and no parameters.

In this case, as soon as the object is created the constructor is called which initializes its data members.

A default constructor is so important for initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly.


C++ Parameterized Constructor

In C++, a constructor with parameters is known as a parameterized constructor. These are the constructors with parameter.
Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument. This is the preferred method to initialize member data.

For Example:-


Example 2: C++ program to calculate the area of a Rectangle

To print the content of a void pointer, we use the static_cast operator. It converts the pointer from void* type to the respective data type of the address the pointer is storing:

// C++ program to understand Parameterized Constructor
                                      
#include <iostream>
using namespace std;

// declare a class
class Rect {
   private:
    double length;
    double height;

   public:
    // create parameterized constructor
    Rect(double len, double hgt) {
        // initialize private variables
        length = len;
        height = hgt;
    }

    double calculateArea() {
        return length * height;
    }
};

int main() {
    // create object and initialize data members
    Rect rect1(5.0, 10.5);
    Rect rect2(6.0, 8.4);

    cout << "The Area of Rectangle 1: " << rect1.calculateArea() << endl;
    cout << "The Area of Rectangle 2: " << rect2.calculateArea() << endl;

    return 0;
}

Output

The Area of Rectangle 1: 52.5
The Area of Rectangle 2: 50.4

Here, we have created a parameterized constructor Rect() that has 2 parameters: double len and double hgt. The values contained in these parameters are used to initialize the member variables length and height.

When we create an object of the Cube class, we pass the values for the member variables as arguments. The code for this is:

Side side1(5.0, 10.5);
Side side2(6.0, 8.4);

With the member variables thus initialized, we can now calculate the area of the side with the calculateArea() function.


Uses of Parameterized Constructor:

  • It is used to initialize the various data elements of different objects with different values when they are created.
  • It is used to overload constructors.

C++ Copy Constructor

A copy constructor is a member function which initializes an object using another object of the same class. These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object.

For Example:-


Example 3: C++ Program to understand Copy Constructor

#include <iostream>
using namespace std;

// declare a class
class Rect {
   private:
    double length;
    double height;

   public:

    // parameterized constructor
    Rect(double len, double hgt) {
        // initialize private variables
        length = len;
        height = hgt;
    }

    // copy constructor with a Rect object as parameter
    Rect(Rect &obj) {
        // initialize private variables
        length = obj.length;
        height = obj.height;
    }
    double calculateArea() {
        return length * height;
    }
};

int main() {

    // create an object of Rect class
    Rect rect1(5.0, 10.5);

    // print area of rect1
    cout << "The Area of Rectangle 1: " << rect1.calculateArea() << endl;

    // copy contents of room1 to another object rect2
    Rect rect2 = rect1;

    // print area of rect2
    cout << "The Area of Rectangle 2: " << rect2.calculateArea() << endl;

    return 0;
}

Output

The Area of Rectangle 1: 52.5
The Area of Rectangle 2: 52.5

In this program, we have used a copy constructor to copy the contents of one object of the Rect class to another. The code of the copy constructor is:

Rect(Rect &obj) {
    length = obj.length;
    height = obj.height;
}

Notice that the parameter of this constructor has the address of an object of the Rect class.

We then assign the values of the variables of the first object to the corresponding variables of the second object. This is how the contents of the object is copied.

In main(), we then create two objects rect1 and rect2 and then copy the contents of the first object to the second with the code

Rect rect2 = rect1;

Note: A constructor is primarily used to initialize objects. They are also used to run a default code when an object is created.


Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of Constructors in C++.

Keep Learning : )

In the next tutorial, you'll learn about C++ Destructors.

- Related Topics