Lesson 135 +10 XP

Constructor Overloading

Constructor Overloading

A class can have more than one constructor, each with a different list of parameters. This is constructor overloading. The compiler picks the right constructor from the arguments you pass.

Why have more than one

Different situations ask for different setups. Let one constructor with no parameters build a default car, and another with arguments build a specific one:

class Car {
public:
  string brand;
  int year;
  Car() {                // no parameters
    brand = "Unknown";
    year = 0;
  }
  Car(string b, int y) {   // two parameters
    brand = b;
    year = y;
  }
};

Picking the right one

Both constructors share the name Car. They differ in their parameter lists, and the arguments of each call decide the winner:

Car a;                  // matches the no-parameter version
Car b("BMW", 2023);     // matches the two-parameter version

Defaults act like overloading

Default parameter values give you extra flexibility with a single definition:

Car(string b, int y = 2022) { ... }
Car c("Audi");          // year gets the default 2022

TL;DR

  • Overloading = several constructors with the same class name.
  • They must differ by their parameter list (count or types).
  • The compiler picks the one matching the call's arguments.
  • Default parameter values can stand in for a few overloads.