C++ Constructor Overloading

πŸ” C++ Constructor Overloading

Constructor overloading means having more than one constructor in a class, each with a different parameter list.
It allows objects to be created in multiple ways.


πŸ”Ή 1. Why Use Constructor Overloading?

  • Flexible object creation

  • Different initialization scenarios

  • Cleaner and more readable code

  • Common in real-world classes


πŸ”Ή 2. Basic Example

class Box {
public:
int length, width, height;

// Default constructor
Box() {
length = width = height = 0;
}

// Parameterized constructor (1 parameter)
Box(int l) {
length = width = height = l;
}

// Parameterized constructor (3 parameters)
Box(int l, int w, int h) {
length = l;
width = w;
height = h;
}
};


πŸ”Ή 3. Creating Objects Using Different Constructors

int main() {
Box b1; // default constructor
Box b2(5); // one-parameter constructor
Box b3(2, 3, 4); // three-parameter constructor
}

πŸ”Ή 4. Constructor Overloading with Initialization List (Recommended)

class Student {
public:
int id;
string name;

Student() : id(0), name("Unknown") {}

Student(int i) : id(i), name("Unknown") {}

Student(int i, string n) : id(i), name(n) {}
};

βœ” Faster
βœ” Cleaner
βœ” Best practice


πŸ”Ή 5. Overloading vs Default Parameters

Constructor Overloading

class Test {
public:
Test() {}
Test(int x) {}
};

Default Parameter Constructor

class Test {
public:
Test(int x = 0) {}
};

⚠️ Avoid mixing both β†’ ambiguity.


πŸ”Ή 6. Copy Constructor and Overloading

class Demo {
public:
int x;

Demo(int val) {
x = val;
}

Demo(const Demo &d) { // copy constructor
x = d.x;
}
};


πŸ”Ή 7. Explicit Constructors (Avoid Ambiguity)

class Demo {
public:
explicit Demo(int x) {
cout << x;
}
};

Prevents:

Demo d = 10; // ❌ not allowed

❌ Common Mistakes

❌ Same Parameter List

Box(int a);
Box(int b); // ❌ error (same signature)

❌ Ambiguous Constructors

Box(int a);
Box(int a, int b = 0); // ❌ ambiguous

πŸ” How Constructor Overloading Works

  • Compiler chooses constructor based on:

    • Number of arguments

    • Data types

    • Order of parameters


πŸ“Œ Summary

  • Multiple constructors in one class

  • Different parameter lists

  • Enables flexible object creation

  • Use initialization lists

  • Avoid ambiguity with default parameters

You may also like...