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:
class Foo { public: Foo(char x, int y = 0); // combines constructors (char) and (char, int) // ... };
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!