CKTIS / C++
`default` in C++: `Product() = default;` vs. the `default:` label
`Product() = default;` explicitly declares a default constructor and lets the compiler implement it. The `default:` label in a `switch` marks where execution starts when no `case` matches.
Version: ISO C++23; implementation support may vary
Syntax
struct Product {
Product() = default;
};Product() = default; is an explicitly defaulted definition of the no-argument constructor. The = default syntax is neither an assignment nor a default argument: it tells the compiler to define the constructor according to the language rules. Both overloads can coexist. If you keep Product(int) but remove Product() = default;, the compiler will not implicitly declare a no-argument constructor.
The default constructor uses default member initializers such as int stock = 3;. The = default syntax does not by itself zero all data members. The constructor can also be defined as deleted, for example if the class has a reference member with no default member initializer. Trying to use that constructor is a compile-time error.
In a switch, default: is an optional label, not a constructor definition. Control jumps to it if no case matches the condition value. Each switch can have at most one default: label of its own.
Examples
#include <iostream>
struct Product {
int stock = 3;
Product() = default;
explicit Product(int count) : stock{count} {}
};
int main() {
Product item;
Product bulk{12};
std::cout << "default constructor: " << item.stock << '\n';
std::cout << "int constructor: " << bulk.stock << '\n';
switch (item.stock) {
case 0:
std::cout << "out of stock\n";
break;
default:
std::cout << "switch default\n";
break;
}
}Result
default constructor: 3 int constructor: 12 switch default
`Product item;` calls `Product()` and sets `stock` to `3` through the member initializer. `Product bulk{12};` selects `Product(int)` and sets `stock` to `12`. In the `switch`, `3` does not match `case 0`, so control jumps to `default:`.
Related lessons
- C++ · Lesson 42 · Intermediate · Version: 2