• Articles
  • Tutorials
  • Interview Questions

What is a Constructor in C++?

What is a Constructor in C++?

Before diving into constructors in C++, it’s essential to have a strong understanding of the fundamentals of the language. With a firm grasp of these prerequisites, constructors, which can seem like an abstract concept, become easier to grasp—with concepts like language semantics and basics, object-oriented programming, classes and objects, functions in C++, and exception handling in C++.

Check out our Youtube video on C programming language for absolute beginners.

Video Thumbnail

Introduction to Constructors in C++

Introduction to Constructors in C++

A constructor in C++ is a special member function responsible for initializing the data members of an object when the same is created. 

  • A constructor’s nomenclature closely resembles the class. It has the same name as the class with no return type.
  • Constructors are invoked automatically when an object is created and can take arguments to initialize the object’s data members.
  • It is usually declared in public scope. However, it can be declared in private scope, as well.

For instance, consider a class called Car with make, model, and year as its data members. We can create a constructor for the Car class that takes arguments for each of these data members and initializes them when a Car object is created.

Here’s a basic C++ constructor example:

#include <iostream>
class MyClass {
public:
    MyClass() { std::cout << "Constructor called!" << std::endl; }
};
int main() {
    MyClass obj;
    return 0;
}

In this, we’ve retained the essential parts of the previous example while removing unnecessary whitespace and comments. The output and functionality remain the same:

Constructor called!

Keep in mind that this is a minimal example meant to showcase the constructor’s basic usage. In real-world applications, constructors often have parameters and perform more complex initialization tasks.

Types of Constructors in C++

Types of Constructors in C++

As mentioned above, constructors are special member functions responsible for initializing the objects of a class. Understanding the different types of constructors is essential for developing robust and efficient C++ programs. There are three types of constructors in C++, namely default, parameterized, and copy constructors.

Default Constructor:

A default constructor takes no arguments. Thus, it is called, by default, when an object is created without any arguments. The default constructor initializes the data members of an object to their default values.

Example:

class Intellipaat {
  public:
    int value;
    string name;
    Intellipaat() { // default constructor
      value = 0;
      name = "default";
    }
};

Get 100% Hike!

Master Most in Demand Skills Now!

Parameterized Constructor:

A parameterized constructor takes one or more arguments. It is used to initialize the data members of an object, with specific values that the user provides.

Example:

class Intellipaat {
  public:
    int value;
    string name;
    Intellipaat(int n, string str) { // parameterized constructor
      value = n;
      name = str;
    }
};

Copy Constructor:

A C++ copy constructor creates an object by initializing it with an existing object of the same class. Simply put, it creates a new object with the same values as an existing object.

Example:

class Intellipaat {
  public:
    int value;
    string name;
    Intellipaat(const Intellipaat &obj) { // copy constructor
      value = obj.value;
      name = obj.name;
    }
};

Constructor Overloading

C++ Constructor overloading is one of the handiest features of C++. It empowers developers to define multiple constructors for each of the classes that they design. This means that classes can offer more flexibility when creating objects, thus providing options like varying numbers or types of initial inputs that are tailored specifically to the needs of each program.

For the purpose of illustration, let’s say that we’re working on building a ‘Rectangle‘ class, representing the shape of rectangles through their length and width measurements. We could use this feature by setting up two distinct constructors—one without any initial inputs, setting both length and width at 1, and another designed for custom lengths and widths through specified input values.

class Rectangle {
  private:
    int length;
    int width;
  public:
    Rectangle() {
      length = 1;
      width = 1;
    }
    Rectangle(int l, int w) {
      length = l;
      width = w;
    }
};

With the following two constructors, we can create Rectangle objects in different ways:

Rectangle r1; // Uses default constructor with no parameters
Rectangle r2(4, 5); // Uses constructor with two integer parameters

In addition to overloading constructors with different parameters, we can overload constructors with default parameter values, as well. For example:

class Circle {
  private:
    double radius;
  public:
    Circle() {
      radius = 1.0;
    }
    Circle(double r) {
      radius = r;
    }
    Circle(double r, double x, double y) {
      radius = r;
      // Code to set x and y coordinates
    }
};

In this example, we have defined three constructors for the class, Circle – one with no parameters, another with a single parameter for the radius, and another with three parameters, one each for the radius, x, and y coordinates. By providing default values for the x/y parameters in the third constructor, we can create a Circle object with just a radius parameter or all three parameters as shown below.

Circle c1; // Uses C++ default constructor with no parameters
Circle c2(2.5); // Uses constructor with single double parameter
Circle c3(3.0, 1.0, 2.0); // Uses constructor with three double parameters
Circle c4(4.0, 3.0); // Uses constructor with default y-coordinate value

Benefits of Using Constructors

Benefits of Using Constructors

Constructor is one of the vital features of OOPS-based programming languages. It provides several benefits to the programmer and developers with respect to code organization, memory management, and initialization. 

Below mentioned are some of the key benefits of using constructors while coding:

  • Initialization: Constructors provide a way to initialize the data members of an object when created. A constructor ensures that the object is valid from the beginning and eliminates the need for separate initialization functions.
  • Code organization: Constructors help organize the code by grouping related operations. By defining constructors within a class, the programmer can ensure that the initialization code is located at one location, making it easier to maintain and modify.
  • Encapsulation: Constructors can enforce encapsulation by setting the data members of the class to private and providing public constructors to create and initialize the object. It helps in protecting the data contained within the object from external manipulation and ensures that the object is always in a valid state.
  • Default constructors: When no constructor is defined, the compiler generates a default constructor that initializes all data members to their default values. Constructors can be helpful when working with arrays of objects or creating objects without providing specific initialization values.
  • Inheritance: Constructors can be inherited from base classes and overridden in derived classes, allowing for customization of initialization behavior. It helps maintain consistency and flexibility across related classes.
  • Memory management: Constructors can manage memory allocation and deallocation for dynamically allocated objects. They ensure that memory is properly allocated and deallocated, preventing memory leaks and other issues.

Conclusion

Constructors offer several benefits, including ensuring that an object is properly initialized before it can be used, improving code readability and maintainability, and allowing for more flexibility in object creation through constructor overloading. Understanding the various types of constructors available and how they can be used helps developers create more robust and effective C++ programs.

Incorporating constructors into your programming knowledge can be a valuable asset for creating efficient, readable, and maintainable C++ code. With the ability to initialize data members and provide additional flexibility in object creation, constructors can significantly enhance the functionality and usability of your C++ programs. By utilizing the benefits of constructors, developers can streamline their code and focus on creating innovative and dynamic software solutions.

Course Schedule

Name Date Details
Python Course 23 Nov 2024(Sat-Sun) Weekend Batch View Details
30 Nov 2024(Sat-Sun) Weekend Batch
07 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.