ProgrammingC++ Developer

How does the default constructor work in C++? What happens if no constructors are declared in the class, and if other constructors are explicitly declared but the default constructor is not?

Pass interviews with Hintsage AI assistant

Answer

In C++, a default constructor is a constructor with no parameters or with parameters that all have default values. If no constructors are declared in the class, the compiler will automatically generate a public default constructor. However, if at least one any other constructor (for example, a constructor with parameters) is declared, the automatically provided default constructor will not be generated. If a default constructor is needed in such a class, it must be explicitly declared (for example, using ClassName() = default;).

Code Example

class Foo { public: Foo(int x) {} // User-defined constructor // Foo() default will not be generated by the compiler! }; Foo f; // Compilation error — no default constructor!

To explicitly create a default constructor in this case, one should add:

class Foo { public: Foo() = default; Foo(int x) {} };

Trick Question

"If you only have one constructor with parameters, can you create objects of this class without parameters? Why?"

Answer: No! Because, if any constructor is declared, the compiler does not automatically add the default constructor. To create objects without parameters, a default constructor must be explicitly added to the declaration.


Examples of real errors due to misunderstanding the subtleties of the topic.


Story

In a large project, a class hierarchy for data serialization was written where all "child" classes only had a specific constructor with parameters. After refactoring, it turned out that when using STL containers (for example, std::vector) with these classes, compilation failed: the container required a default constructor, which was absent. The problem was resolved only after explicitly declaring the default constructor.


Story

In a project using templating, one of the adapter classes declared only a parameterized constructor for passing resources. At the same time, one of the libraries required the presence of a default constructor for correct functioning (creating temporary objects through template types). Mysterious linking errors occurred, which could not be explained for a long time until an explicit default constructor was implemented.


Story

In the code, there was a migration from C++98 to C++11, and an attempt to use "= default" to explicitly declare the default constructor. In older compilers, errors occurred or new syntax constructs were ignored. This revealed that not all developers understand the difference between an explicitly implemented default constructor, one generated by the compiler, and the new syntax "= default".