๐ What Are Multiple Constructors?
In C++, a class can have more than one constructor. This concept is called Constructor Overloading โ where multiple constructors have the same name (class name) but different parameter lists.
It allows objects to be created in different ways, depending on how much information is available at the time of creation.
โ Why Use Multiple Constructors?
- To give flexibility in object initialization.
- To allow initialization with default values, partial data, or full data.
- Improves code readability and reusability.
๐ง Syntax:
class ClassName {
public:
ClassName(); // Default constructor
ClassName(int); // Parameterized constructor (1 param)
ClassName(int, string); // Parameterized constructor (2 params)
};
๐งช Example: Multiple Constructors
#include <iostream>
using namespace std;
class Student {
int roll;
string name;
public:
// Default Constructor
Student() {
roll = 0;
name = "Unknown";
}
// Constructor with one parameter
Student(int r) {
roll = r;
name = "Unknown";
}
// Constructor with two parameters
Student(int r, string n) {
roll = r;
name = n;
}
void display() {
cout << "Roll No: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1; // Calls default constructor
Student s2(101); // Calls constructor with 1 parameter
Student s3(102, "Alice"); // Calls constructor with 2 parameters
s1.display();
s2.display();
s3.display();
return 0;
}
๐ฏ Output:
Roll No: 0, Name: Unknown
Roll No: 101, Name: Unknown
Roll No: 102, Name: Alice
๐ง How It Works:
- C++ decides which constructor to use based on the number and types of arguments provided when creating an object.
- This is an example of function overloading applied to constructors.
๐ Rules of Constructor Overloading
Rule | Description |
---|---|
โ Constructor names must be the same (i.e., same as the class). | |
โ Each constructor must have a unique parameter list. | |
โ Return type is not used to differentiate constructors. |
๐ Summary
- A class can have multiple constructors to support different ways of creating objects.
- Known as constructor overloading.
- Useful for flexibility and clean coding.
- You can provide default, partial, or complete initialization.