Skip to content

Parameterized constructors

๐ŸŽฏ 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 values 101 and "Alice".
  • These values are assigned directly to the data members.

๐Ÿ’ก Advantages of Parameterized Constructors

BenefitExplanation
Custom InitializationSet values at the time of object creation.
Better ReadabilityCode becomes shorter and cleaner.
No Need for SettersReduces 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.