Classes, Structs and Enums

Multiple Constructors with the Same Name

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

Abstract art representing computer programming

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 computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved