0
0
C++programming~5 mins

Constructor overloading in C++

Choose your learning style9 modes available
Introduction

Constructor overloading lets you create objects in different ways using the same class. It helps you set up objects with different starting values easily.

When you want to create an object with no initial data.
When you want to create an object with some initial values provided.
When you want to create objects with different sets of starting information.
When you want to make your class flexible for different situations.
Syntax
C++
class ClassName {
public:
    ClassName();          // Constructor with no parameters
    ClassName(int x);     // Constructor with one parameter
    ClassName(int x, int y); // Constructor with two parameters
};
Each constructor has the same name as the class but different parameters.
The compiler decides which constructor to use based on the arguments you provide.
Examples
This class has three constructors with different numbers of parameters.
C++
class Box {
public:
    Box() { /* no parameters */ }
    Box(int l) { /* one parameter */ }
    Box(int l, int w) { /* two parameters */ }
};
Shows how different constructors are called based on arguments.
C++
Box b1;       // Calls Box()
Box b2(5);     // Calls Box(int l)
Box b3(5, 10); // Calls Box(int l, int w)
Sample Program

This program shows three ways to create Box objects using constructor overloading. Each object has different starting values.

C++
#include <iostream>
using namespace std;

class Box {
public:
    int length, width;

    Box() {
        length = 0;
        width = 0;
    }

    Box(int l) {
        length = l;
        width = 0;
    }

    Box(int l, int w) {
        length = l;
        width = w;
    }

    void display() {
        cout << "Length: " << length << ", Width: " << width << endl;
    }
};

int main() {
    Box box1;
    Box box2(5);
    Box box3(5, 10);

    box1.display();
    box2.display();
    box3.display();

    return 0;
}
OutputSuccess
Important Notes

Constructor overloading helps keep your code clean and easy to use.

If you don't define any constructor, the compiler provides a default one with no parameters.

Be careful to avoid constructors with the same parameter types and counts, as it causes errors.

Summary

Constructor overloading means having multiple constructors with different parameters.

It allows creating objects with different initial data easily.

The right constructor is chosen automatically based on the arguments you give.