C++ Constructor Overload and Delegating Constructors
Constructor overload means one class has more than one constructor.
Series navigation: Previous: Constructors and object lifetime | Next: Default constructor, copy constructor, move constructor
Each constructor has a different parameter list.
The compiler chooses the constructor that matches the arguments.
Initialize private members
Private members should usually be initialized in the constructor initializer list.
This part initializes the private members:
Prefer this over assigning inside the constructor body:
The initializer list constructs the members directly.
Assignment in the body first creates the members, then changes them.
Constructor overload
Usage:
Delegating constructor
A constructor can call another constructor from the same class.
This is called a delegating constructor.
Here:
The default constructor calls the main constructor.
And:
The name-only constructor also calls the main constructor.
This keeps initialization logic in one place.
Full example
Expected idea:
The delegated constructor runs first.
Then the body of the constructor that delegated runs.
Important rule
When a constructor delegates to another constructor, it cannot also initialize members in the same initializer list.
This is valid:
This is not valid:
Choose one:
- delegate to another constructor
- initialize members directly
Rule of thumb
- Use overloaded constructors when users need different ways to create the object.
- Use one main constructor for the real initialization.
- Make smaller constructors delegate to the main constructor.
- Initialize private members in the initializer list.
- Keep constructor body for validation, logging, or extra logic.
Run online
Copy the full example and run it in the embedded OneCompiler C++ runtime.
Other online compilers: OneCompiler | Compiler Explorer | Wandbox
Run locally
Save the full example as main.cpp:
Series navigation: Previous: Constructors and object lifetime | Next: Default constructor, copy constructor, move constructor