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).
Answers to questions are automatically generated and may not have been reviewed.
A crash tour on how we can create custom types in C++ using classes, structs and enums