Delegating Constructors
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 23 of 104.
When you have multiple constructors that share common initialization logic, you can use delegating constructors to avoid code duplication. A delegating constructor calls another constructor of the same class in its initializer list.
class Player {
std::string name;
int health;
int level;
public:
// Primary constructor - does the actual work
Player(std::string n, int h, int lvl)
: name(n), health(h), level(lvl) {}
// Delegates to the primary constructor
Player(std::string n) : Player(n, 100, 1) {}
// Default constructor delegates too
Player() : Player("Unknown") {}
};The delegation happens in the initializer list using the class name followed by arguments. When Player() is called, it delegates to Player(std::string), which then delegates to the three-parameter constructor. The chain executes from the target constructor back to the original.
There's one important rule: a delegating constructor cannot have other members in its initializer list. The delegation must be the only item:
class Item {
int id;
int value;
public:
Item(int i, int v) : id(i), value(v) {}
// Error! Cannot mix delegation with member initialization
// Item(int i) : Item(i, 0), id(i) {}
// Correct - delegation only
Item(int i) : Item(i, 0) {}
};Delegating constructors help centralize initialization logic in one place, making your code easier to maintain and less prone to errors from duplicated code.
Challenge
EasyLet's build a connection settings system that demonstrates how delegating constructors can eliminate code duplication by chaining constructor calls together.
You'll create two files to organize your code:
Connection.h: Define aConnectionclass that represents a network connection with various configuration options. Your class should have:- Private members:
host(string),port(int),timeout(int in seconds), andsecure(bool) - A primary constructor that takes all four parameters and initializes all members using an initializer list. This constructor should print
"Connection configured: <host>:<port>" - A constructor taking only
hostandportthat delegates to the primary constructor withtimeoutdefaulting to30andsecuredefaulting tofalse - A constructor taking only
hostthat delegates to the two-parameter constructor withportdefaulting to80 - A default constructor that delegates to the one-parameter constructor with
hostdefaulting to"localhost" - A
getInfo()method that returns a string in the format:"<host>:<port> (timeout: <timeout>s, secure: <yes/no>)"
- Private members:
main.cpp: Demonstrate the delegation chain by creating connections using different constructors. Read a host name and port number from input (each on a separate line), then:- Create a
Connectionusing the default constructor - Create a
Connectionusing only the host from input - Create a
Connectionusing both host and port from input - Create a
Connectionwith the input host, input port, timeout of60, and secure set totrue - Print
getInfo()for each connection, one per line
- Create a
The delegation chain flows like this: default constructor calls the one-parameter constructor, which calls the two-parameter constructor, which calls the primary four-parameter constructor. This means the "Connection configured" message prints once for each object created, always from the primary constructor.
For the secure status in getInfo(), print "yes" if secure is true, otherwise "no".
Include your header file in main.cpp using #include "Connection.h".
Cheat sheet
A delegating constructor calls another constructor of the same class in its initializer list to avoid code duplication:
class Player {
std::string name;
int health;
int level;
public:
// Primary constructor
Player(std::string n, int h, int lvl)
: name(n), health(h), level(lvl) {}
// Delegates to the primary constructor
Player(std::string n) : Player(n, 100, 1) {}
// Default constructor delegates too
Player() : Player("Unknown") {}
};The delegation happens in the initializer list using the class name followed by arguments. Constructors can form a delegation chain where one delegates to another.
Important rule: A delegating constructor cannot have other members in its initializer list. The delegation must be the only item:
class Item {
int id;
int value;
public:
Item(int i, int v) : id(i), value(v) {}
// Error! Cannot mix delegation with member initialization
// Item(int i) : Item(i, 0), id(i) {}
// Correct - delegation only
Item(int i) : Item(i, 0) {}
};Try it yourself
#include <iostream>
#include <string>
#include "Connection.h"
using namespace std;
int main() {
// Read input
string host;
int port;
cin >> host;
cin >> port;
// TODO: Create a Connection using the default constructor
// TODO: Create a Connection using only the host from input
// TODO: Create a Connection using both host and port from input
// TODO: Create a Connection with input host, input port, timeout=60, secure=true
// TODO: Print getInfo() for each connection, one per line
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container