bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/C++/C++ Classes
C++•C++ Classes

C++ Constructor Overloading

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind C++ Constructor Overloading?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___: string brand;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

In C++, you can have more than one constructor in the same class.
Why Use Constructor Overloading?
Constructor Overloading

Constructor Overloading

In C++, you can have more than one constructor in the same class. This is called constructor overloading .

Each constructor must have a different number or type of parameters , so the compiler knows which one to use when you create an object.

Why Use Constructor Overloading?

  • To give flexibility when creating objects
  • To set default or custom values
  • To reduce repetitive code

Example with Two Constructors

This class has two constructors: one without parameters, and one with parameters:

Runnable example

class Car {
  public: string brand;
  string model;
  Car() {
    brand = "Unknown";
    model = "Unknown";
  }
Car(string b, string m) {
  brand = b;
  model = m;
}
};
int main() {
  Car car1;
  Car car2("BMW", "X5");
  Car car3("Ford", "Mustang");
  cout << "Car1: " << car1.brand << " " << car1.model << "\n";
  cout << "Car2: " << car2.brand << " " << car2.model << "\n";
  cout << "Car3: " << car3.brand << " " << car3.model;
  return 0;
}

Constructor overloading lets you create objects with custom values.

Previous

C++ Constructors

Next

C++ Access Specifiers