bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/C++/C++ Classes
C++•C++ Classes

C++ 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

This chapter

Overview
17

Lessons

49m

Read time

1. C++ OOP2. C++ Classes and Objects3. C++ Class Methods4. C++ Constructors5. C++ Constructor Overloading6. C++ Access Specifiers7. C++ Encapsulation8. C++ The Friend Keyword9. C++ Inheritance10. C++ Multilevel Inheritance11. C++ Multiple Inheritance12. C++ Inheritance Access13. C++ Polymorphism14. C++ Virtual Functions15. C++ Templates16. C++ Files17. C++ Date and Time

On this page

Constructor OverloadingWhy Use Constructor Overloading?Example with Two Constructors