• Home
  • Constructor overloading in C++

Constructor overloading in C++

Constructor overloading in C++ is a technique in which a class can have more than one constructor, with each constructor having a different number of parameters or different types of parameters. This allows the programmer to initialize an object in different ways depending on the data available or the requirements of the program.

For example, consider a class Student that represents a student in a school. The class can have a default constructor that initializes the student’s name to an empty string and age to 0, and a parameterized constructor that takes a string for the name and an integer for the age as arguments.

class Student {
Student() {
name = "";
age = 0;
Student(string n, int a) {
name = n;
age = a;
// Other member functions and variables
string name;
int age;

To create an object of the Student class using the default constructor, you can simply call Student s;. To create an object using the parameterized constructor, you can call Student s("John", 15);.

Constructor overloading is useful when you want to provide multiple options for initializing an object, or when the initialization of an object depends on the availability of certain data. It allows you to create more flexible and efficient code.