Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Constructor Delegation | Constructors and Destructors
C++ OOP
course content

Contenido del Curso

C++ OOP

C++ OOP

1. Fundamentals of OOP
2. Constructors and Destructors
3. Encapsulation Overview
4. Inheritance Overview
5. Polymorphism Overview

Constructor Delegation

Constructor delegation, also known as constructor chaining or constructor forwarding, is a concept in object-oriented programming where one constructor of a class calls another constructor from the same class to perform common initialization tasks.

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.

While it's not necessary to utilize initialization lists for constructor delegation, it is generally considered preferable. However, if there's a specific reason to avoid them, you can opt to call an overloaded constructor from within another constructor instead.

cpp

main

copy
12345678910111213141516
#include <iostream> class Example { public: Example() { Example(0, 0); } Example(int arg1, int arg2) : member1(arg1), member2(arg2) {} int member1, member2; }; int main() { }

Be caution

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.

What is constructor delegation?

Selecciona la respuesta correcta

¿Todo estuvo claro?

Sección 2. Capítulo 5
We're sorry to hear that something went wrong. What happened?
some-alt