Multiple Constructors with the Same Name

How can a class have multiple constructors with the same name?

In C++, a class can have multiple constructors as long as they have different parameter lists. This is known as constructor overloading.

When you create an object, the compiler will choose the constructor that best matches the arguments you provide. For example:

#include <iostream>

class Player {
public:
  Player() {
    std::cout << "Default constructor\n";
  }

  Player(int health) {
    std::cout << "Int constructor\n";
  }

  Player(const std::string& name) {
    std::cout << "String constructor\n";
  }
};

int main() {
  Player p1;            // Default constructor
  Player p2{100};       // Int constructor
  Player p3{"Gandalf"}; // String constructor
}
Default constructor
Int constructor
String constructor

This allows for flexibility in how objects can be initialized. Just make sure each constructor has a unique signature (name + parameter list).

Classes, Structs and Enums

A crash tour on how we can create custom types in C++ using classes, structs and enums

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to Use Classes vs Structs in C++
What are the key differences between classes and structs in C++, and when should I use one over the other?
When to Use Public Inheritance
In what situations is it appropriate to use public inheritance in C++?
When to Use Member Initializer Lists
What are the benefits of using member initializer lists in constructors?
Implicitly-Defined Default Constructors
When does the compiler implicitly define a default constructor for a class?
Using Destructors for Resource Management
How can I use destructors to manage resources in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant