Home >Backend Development >C++ >How Does Constructor Chaining Work in C ?

How Does Constructor Chaining Work in C ?

Susan Sarandon
Susan SarandonOriginal
2025-01-01 14:41:09230browse

How Does Constructor Chaining Work in C  ?

Constructor Chaining in C

Constructor chaining, where one constructor calls another constructor from within its body, is a common practice in C# for initializing objects with varying parameters. C has a similar feature called delegating constructors.

C 11 and Onwards

In C 11 and later versions, delegating constructors can be used to achieve constructor chaining. The syntax is:

class Foo {
public:
  Foo(char x, int y);
  Foo(int y) : Foo('a', y) {}
};

The Foo(int y) constructor calls the Foo(char x, int y) constructor with the default value for x.

C 03 and Earlier Versions

C 03 does not support delegating constructors. However, there are two simulation methods:

  • Default Parameters: Combining multiple constructors with default parameter values.
class Foo {
public:
  Foo(char x, int y = 0);  // combines constructors (char) and (char, int)
  // ...
};
  • Initialization Method: Sharing common code among constructors through a private initialization method.
class Foo {
public:
  Foo(char x);
  Foo(char x, int y);
  // ...
private:
  void init(char x, int y);
};

Foo::Foo(char x)
{
  init(x, x + 7);
  // ...
}

Foo::Foo(char x, int y)
{
  init(x, y);
  // ...
}

void Foo::init(char x, int y)
{
  // ...
}

The above is the detailed content of How Does Constructor Chaining Work in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn