Implicitly-Defined Default Constructors

When does the compiler implicitly define a default constructor for a class?

In C++, a default constructor is a constructor that can be called with no arguments. The compiler will implicitly define a default constructor for a class if:

  1. The class has no user-defined constructors at all.
  2. All data members of the class have a default constructor (or are built-in types).

For example:

class Player {
  int health_;
  std::string name_;
};

Player p1; // OK, implicit default constructor

However, if we define any constructor for the class, the compiler will no longer provide an implicit default constructor:

class Player {
 public:
  Player(int health) : health_{health} {}

 private:
  int health_;
  std::string name_;
};

Player p1;       // Error, no default constructor
Player p2{100};  // OK, using defined constructor

In this case, if we still want a default constructor, we need to define it explicitly:

class Player {
 public:
  Player() = default;  
  Player(int health) : health_{health} {}

 private:
  int health_;
  std::string name_;
};

// OK, using defaulted default constructor
Player p1;

So remember: if you define any constructors for a class, and you want a default constructor, you need to define it explicitly (either by writing it or by using = default).

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?
Multiple Constructors with the Same Name
How can a class have multiple constructors with the same name?
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?
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