Menu
Coddy logo textTech

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 icon

Challenge

Easy

Let'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 a Connection class that represents a network connection with various configuration options. Your class should have:
    • Private members: host (string), port (int), timeout (int in seconds), and secure (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 host and port that delegates to the primary constructor with timeout defaulting to 30 and secure defaulting to false
    • A constructor taking only host that delegates to the two-parameter constructor with port defaulting to 80
    • A default constructor that delegates to the one-parameter constructor with host defaulting to "localhost"
    • A getInfo() method that returns a string in the format: "<host>:<port> (timeout: <timeout>s, secure: <yes/no>)"
  • 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 Connection using the default constructor
    • Create a Connection using only the host from input
    • Create a Connection using both host and port from input
    • Create a Connection with the input host, input port, timeout of 60, and secure set to true
    • Print getInfo() for each connection, one per line

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;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming