Can I call constructor of a member in my Class's constructor?
let say If I have a member bar
of class type foo
in my class MClass
. Can I call constructor of bar in MClass's constructor? If not, then how can I initialize my member bar?
It is a problem of initializing members in composition(aggregation).
The invocation of one constructor from another constructor within the same class or different class is known as constructor chaining in Java. If we have to call a constructor within the same class, we use 'this' keyword and if we want to call it from another class we use the 'super' keyword.
To call one constructor from another constructor is called constructor chaining in java. This process can be implemented in two ways: Using this() keyword to call the current class constructor within the “same class”. Using super() keyword to call the superclass constructor from the “base class”.
No, in C++ you cannot call a constructor from a constructor.
Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.
Yes, certainly you can! That's what the constructor initializer list is for. This is an essential feature that you require to initialize members that don't have default constructors, as well as constants and references:
class Foo { Bar x; // requires Bar::Bar(char) constructor const int n; double & q; public: Foo(double & a, char b) : x(b), n(42), q(a) { } // ^^^^^^^^^^^^^^^^^^^ };
You further need the initializer list to specify a non-default constructor for base classes in derived class constructors.
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