My understanding of constructor chaining is that , when there are more than one constructors in a class (overloaded constructors) , if one of them tries to call another constructor,then this process is called CONSTRUCTOR CHAINING , which is not supported in C++ . Recently I came across this paragraph while reading online material.... It goes like this ...
You may find yourself in the situation where you want to write a member function to re-initialize a class back to default values. Because you probably already have a constructor that does this, you may be tempted to try to call the constructor from your member function. As mentioned, chaining constructor calls are illegal in C++. You could copy the code from the constructor in your function, which would work, but lead to duplicate code. The best solution in this case is to move the code from the constructor to your new function, and have the constructor call your function to do the work of initializing the data.
Does a member function calling the constructor also come under constructor chaining ?? Please throw some light on this topic in C++ .
Constructor chaining is the process of calling one constructor from another constructor with respect to current object. One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by means of constructor overloading) and make code more readable.
1. Constructor overloading allows a class to have more than one constructor that have the same name as that of the class but differ only in terms of number or type of parameters. 1. Constructor chaining is a process of calling the one constructor from another constructor with respect to current object.
Constructor chaining happens with the process of Inheritance in Java. When we are dealing with the parent class constructor, then the constructor of the subclass will first call the constructor of the superclass. This makes sure that the subclass is created with the initialization of the members of the parent class.
C++11 allows constructor chaining (partially). This feature is called "delegating constructors". So in C++11 you can do the following
class Foo { public: Foo(int a) : Foo() { _a = a; } Foo(char* b) : Foo() { _b = b; } Foo() { _c = 1.5; } private: int _a = 0; char* _b = nullptr; double _c; };
However, there is a severe limitation that a constructor that calls another constructor is not allowed to initialize any other members. So you cannot do the following with a delegating constructor:
class Foo { public: Foo(int a) : Foo(), _a(a) { } Foo(char* b) : Foo(), _b(b) { } Foo() { _c = 1.5; } private: int _a = 0; char* _b = nullptr; double _c; };
MSVC++2013 gives compile error "C3511: a call to a delegating constructor shall be the only member-initializer" for the latter code example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With