Constructors In C++

Constructors In C++

With the help of examples, we will learn about C++ constructors and their type in this article. When an object is created in C++, a special method called the constructor is immediately called.

In general, it is utilized to initialize new objects’ data members.

In C++, the class or structure name serves as the name of the constructor. When creating an object, the function Object() { [native code] } is called.

It creates the values, i.e., supplies the object with data, which is why it is referred to as a constructor.

When an object is created, a particular kind of member function called a constructor is immediately invoked.

The following are some differences between constructors and regular functions:

  • The constructor’s name is the same as the class’s
  • Default There isn’t an input argument for constructors. however, input arguments are available for copy and parameterized constructors.
  • There is no return type for constructors.
  • An object’s constructor is invoked automatically upon creation.
  • It must be shown in the classroom’s open area.
  • The C++ compiler creates a default constructor for the object if a constructor is not specified (expects no parameters and has an empty body).

Let’s use a practical example to better understand the different types of constructors in C++. Let’s say you went to a store to get a marker.

What possibilities are available when you wish to purchase a marker? For the first one, you ask for a marker at a store. Therefore, simply asking for a marker without specifying its brand name or color means that you haven’t mentioned anything at all.

As a result, if we merely said, “I need a marker,” he would bring us whatever the most popular marker was in the store or market. And a default constructor is just that! The second method is to go into a store and specify that you want a red marker of the XYZ brand. As a result, you discuss it, and he gives you the marker.

You have thus specified the parameters in this instance. And a parameterized constructor is just that! The third one is when you go shopping and say, “I want a marker like this” (a physical marker on your hand).

The store owner will so notice that marker. Okay, and he will provide you with a fresh marker. Copy that marker then. And a copy constructor is just that!

constructors in C++ do not have a return type and share the same name as the class. For instance,

class  Wall {
  public:
    // create a constructor
    Wall() {
      // code
    }
};

Here, the purpose of The constructor for the class Wall is called Wall(). Take note that the creator

has the same name as the class, is public, and lacks a return type.

C++ Default Constructor

A default constructor is one that accepts no parameters. Wall() in the preceding example is a default constructor.

Example 1: C++ Default Constructor

// C++ program to demonstrate the use of default constructor

#include <iostream>
using namespace std;

// declare a class
class  Wall {
  private:
    double length;

  public:
    // default constructor to initialize variable
    Wall() {
      length = 5.5;
      cout << "Creating a wall." << endl;
      cout << "Length = " << length << endl;
    }
};

int main() {
  Wall wall1;
  return 0;
}

Output

Creating a Wall
Length = 5.5

Here, the Wall() constructor is executed when the wall1 object is constructed. This changes the object’s length variable to 5.5.

Note: The C++ compiler will automatically produce a default function Object() { [native code] } with empty code and no parameters if we don’t define one in our class.

C++ Parameterized Constructor

A constructor that has parameters is referred to as a parameterized constructor in C++. The method used to initialize member data is this one.

Example 2: C++ Parameterized Constructor

// C++ program to calculate the area of a wall

#include <iostream>
using namespace std;

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

  public:
    // parameterized constructor to initialize variables
    Wall(double len, double hgt) {
      length = len;
      height = hgt;
    }

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

int main() {
  // create object and initialize data members
  Wall wall1(10.5, 8.6);
  Wall wall2(8.5, 6.3);

  cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
  cout << "Area of Wall 2: " << wall2.calculateArea();

  return 0;
}

Output

Area of Wall 1: 90.3
Area of Wall 2: 53.55

The constructor Wall() in this example has two parameters: double len and double hgt. The length and height member variables are initialized using the values found in these arguments.

The values for the member variables are passed as arguments when we create an object of the Wall class. This is coded as:

Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);

We can now use the calculateArea() function to get the area of the wall since the member variables have been initialized.

C++ Copy Constructor

In C++, data from one object is copied to another using the copy constructor.

Example 3: C++ Copy Constructor

#include <iostream>
using namespace std;

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

  public:

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

    // copy constructor with a Wall object as parameter
    // copies data of the obj parameter
    Wall(Wall &obj) {
      length = obj.length;
      height = obj.height;
    }

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

int main() {
  // create an object of Wall class
  Wall wall1(10.5, 8.6);

  // copy contents of wall1 to wall2
  Wall wall2 = wall1;

  // print areas of wall1 and wall2
  cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
  cout << "Area of Wall 2: " << wall2.calculateArea();

  return 0;
}

Output

Area of Wall 1: 90.3
Area of Wall 2: 90.3

To replicate the contents of one Wall class object to another in this program, we utilized the copy constructor. The copy constructor’s code is as follows:

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

Keep in mind that the address of an object belonging to the Wall class is contained in the constructor’s parameter.

After that, we call the copy constructor to assign the values of the obj object’s variables to their equivalent objects’ variables. The object’s contents are replicated in this manner.

We then make two objects, wall1 and wall2, in main(), and copy the data from wall1 to wall2:

// copy contents of wall1 to wall2
Wall wall2 = wall1;

Here, the wall2 object runs its copy constructor with the input &obj = &wall1, supplying the address of the wall1 object.

Note: Initializing objects is the main purpose of a Constructors in C++. When an object is formed, they are also utilized to execute default code.

You may like:

Structure and Function In C++

This Post Has One Comment

Leave a Reply