Constructor overloading in C++ allows a class to have multiple constructors with different parameter lists. Each constructor can be used to initialize objects in various ways, providing flexibility and convenience to the users of the class. The appropriate constructor is automatically chosen based on the arguments provided during object creation.
Syntax for Constructor Overloading:
class ClassName {
public:
// Constructor 1
ClassName();
// Constructor 2
ClassName(parameters);
// Constructor 3
ClassName(parameters, ...);
// Add more constructors as needed
};
Example of Constructor Overloading:
#include <iostream>
using namespace std;
class Box {
private:
double length;
double width;
double height;
public:
// Constructor 1: Default constructor
Box() {
length = 1.0;
width = 1.0;
height = 1.0;
}
// Constructor 2: Constructor with one parameter
Box(double side) {
length = side;
width = side;
height = side;
}
// Constructor 3: Constructor with three parameters
Box(double l, double w, double h) {
length = l;
width = w;
height = h;
}
// Method to calculate and return the volume of the box
double calculateVolume() {
return length * width * height;
}
};
int main() {
// Using different constructors to create objects
Box box1; // Default constructor called
Box box2(4.0); // Constructor with one parameter called
Box box3(2.0, 3.0, 4.0); // Constructor with three parameters called
// Calculate and display the volumes of the boxes
cout << "Volume of box1: " << box1.calculateVolume() << endl;
cout << "Volume of box2: " << box2.calculateVolume() << endl;
cout << "Volume of box3: " << box3.calculateVolume() << endl;
return 0;
}
In this example, the Box
class has three constructors: a default constructor that sets all dimensions to 1.0, a constructor with one parameter that sets all dimensions to the given value, and a constructor with three parameters that sets the individual dimensions. The appropriate constructor is chosen based on the number and types of arguments provided when creating Box
objects.