Latest Questions UpdateCategory: Computer and ITWhat is constructor overloading in C++?
Rajiv Sharma asked 2 months ago

plain its types.What is constructor overloading in C++?

1 Answers
Education Desk Staff answered 1 month ago

Constructor Overloading in C++

Constructor overloading in C++ refers to the ability to define multiple constructors within a single class, each with a different number or type of parameters. This enables the creation of objects in different ways, depending on the specific needs of the program.

When a constructor is called, the compiler determines which constructor to invoke by matching the arguments provided in the object initialization to the corresponding constructor signature.

Key Features:

  1. Same name: All constructors have the same name as the class.
  2. Different parameter lists: Each constructor has a unique combination of parameters (number, type, or order).
  3. Compile-time polymorphism: Constructor overloading is an example of function overloading (a type of compile-time polymorphism).

Example of Constructor Overloading:

“`cpp

include

using namespace std;

class Rectangle {

private:

int length;

int width;

public:

// Default constructor

Rectangle() {

length = 0;

width = 0;

}

// Parameterized constructor

Rectangle(int l, int w) {

length = l;

width = w;

}

// Constructor with one parameter

Rectangle(int side) {

length = side;

width = side; // For a square

}

void display() {

cout << \”Length: \” << length << \”, Width: \” << width << endl;

}

};

int main() {

Rectangle r1; // Calls default constructor

Rectangle r2(10, 5); // Calls parameterized constructor

Rectangle r3(7); // Calls constructor with one parameter

r1.display();

r2.display();

r3.display();

return 0;

}

---

### Output:

Length: 0, Width: 0

Length: 10, Width: 5

Length: 7, Width: 7

How Constructor Overloading Works:

  1. When creating an object, the compiler matches the arguments passed during the object\’s initialization to the corresponding constructor signature.
  2. If no match is found, the compiler throws an error.

Benefits of Constructor Overloading:

    • Flexibility: Allows creating objects with different initial values.
    • Ease of use: Reduces the need for multiple initialization methods.
    • Code reusability: Reuses the same constructor’s name with different parameter lists, simplifying code readability.

Important Notes:

    • The correct constructor is chosen at compile-time based on the arguments.
    • If no constructor is defined, C++ provides a default constructor automatically.
    • Overloaded constructors can call each other using the this keyword, although it’s not required.