Home >Backend Development >C++ >Does C Support Constructor Chaining, and How Does It Compare to C#?
As a C# developer, you may be familiar with the ability to call other constructors from within a constructor. In C#, this is known as constructor chaining. Is there a similar feature in C ?
In C 11 and later versions, constructor chaining is supported through delegating constructors. The syntax is slightly different from C#:
class Foo { public: Foo(char x, int y) {} Foo(int y) : Foo('a', y) {} };
In this example, the constructor Foo(int y) delegates to the constructor Foo(char x, int y) with x set to 'a'.
Unfortunately, constructor chaining is not directly supported in C 03. However, there are two main options for simulating this behavior:
1. Default Parameters:
You can combine multiple constructors by providing default values for some parameters:
class Foo { public: Foo(char x, int y = 0); // Combines constructors Foo(char) and Foo(char, int) };
2. Init Method:
Extract the common code into a private 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, int(x) + 7) {} Foo::Foo(char x, int y) : init(x, y) {} void Foo::init(char x, int y) { // Shared initialization code }
While these techniques do not provide true constructor chaining, they allow for similar functionality.
The above is the detailed content of Does C Support Constructor Chaining, and How Does It Compare to C#?. For more information, please follow other related articles on the PHP Chinese website!