Course Content
C++ OOP
C++ OOP
Constructor Delegation
Constructor delegation (also called constructor chaining or forwarding) lets one constructor call another within the same class to reuse common initialization logic.
Syntax of Constructor Delegation
Constructor delegation is usually used within the syntax of an initialization list. It involves the use of the colon (:
) operator, followed by the constructor you want to delegate to, and then any additional arguments or parameters that need to be passed.
user_account
class UserAccount { public: // Primary constructor UserAccount(int userId, int accessLevel) : userId(userId), accessLevel(accessLevel) { // Constructor body } // Delegating constructor (default accessLevel) UserAccount(int userId) : UserAccount(userId, 0) { // Constructor body } int userId; int accessLevel; };
Using initialization lists for constructor delegation is not required, but it's generally recommended for clarity and performance. If needed, you can call an overloaded constructor from another constructor instead.
point
#include <iostream> class Point { public: // Delegating constructor to initialize default point at origin Point() { Point(0, 0); } // Main constructor Point(int x, int y) : x(x), y(y) {} int x, y; };
Potential infinite recursion may occur when using constructor delegation. Ensure constructors are structured to avoid recursive invocation loops
Constructors delegation provide multiple benefits in object-oriented programming and are convenient to use, despite any initial complexity they may seem to have.
Thanks for your feedback!