๐ฏ What is a Parameterized Constructor?
A parameterized constructor is a constructor that takes arguments (parameters) to initialize an object with specific values at the time of its creation.
โ Why Use It?
- To initialize objects with custom values.
- Avoids the need to write separate setter functions for basic initialization.
- Makes object creation more flexible and powerful.
๐ง Syntax:
class ClassName {
public:
ClassName(parameter_list) {
// initialization code
}
};
๐งช Example: Using Parameterized Constructor
#include <iostream>
using namespace std;
class Student {
public:
int rollNo;
string name;
// Parameterized Constructor
Student(int r, string n) {
rollNo = r;
name = n;
}
void display() {
cout << "Roll No: " << rollNo << ", Name: " << name << endl;
}
};
int main() {
Student s1(101, "Alice"); // Constructor is called with arguments
Student s2(102, "Bob");
s1.display();
s2.display();
return 0;
}
๐ฏ Output:
Roll No: 101, Name: Alice
Roll No: 102, Name: Bob
๐ How It Works:
- When you create the object
Student s1(101, "Alice");
, the constructor is called with the values101
and"Alice"
. - These values are assigned directly to the data members.
๐ก Advantages of Parameterized Constructors
Benefit | Explanation |
---|---|
Custom Initialization | Set values at the time of object creation. |
Better Readability | Code becomes shorter and cleaner. |
No Need for Setters | Reduces the need for separate functions like setData() . |
๐ง Real-Life Analogy
Imagine ordering a pizza. A default constructor gives you a plain pizza.
But a parameterized constructor lets you customize it: size, crust, and toppings โ all at once!
๐ Constructor Overloading (Bonus)
You can create multiple constructors with different parameters in the same class.
class Student {
public:
Student() {
cout << "Default Constructor" << endl;
}
Student(int r) {
cout << "Roll No: " << r << endl;
}
Student(int r, string n) {
cout << "Roll No: " << r << ", Name: " << n << endl;
}
};
๐งพ Summary
- A parameterized constructor takes arguments to initialize an object.
- It’s useful for setting custom values at the time of object creation.
- Improves code efficiency, clarity, and object control.
- It can be overloaded with different parameter sets.