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

Зміст курсу

C++ OOP

C++ OOP

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

book
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.

h

Example

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

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?

What is constructor delegation?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 5
We're sorry to hear that something went wrong. What happened?
some-alt