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).
Through initializer list, if base class doesn't have a default constructor.
Like this:
If your member constructor wants parameters, you can pass them. They can be expressions made from the class constructor parameters and already-initialized types.
Remember: members are initialized in the order they are declared in the class, not the order they appear in the initialization list.
Yes, you can:
The output is:
View this on ideone.com
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:
You further need the initializer list to specify a non-default constructor for base classes in derived class constructors.
Yes, you can. This is done in the initialization list of your class. For example:
This will construct
bar
with the arguments passed in. Normally, the arguments will be other members of your class or arguments that were passed to your constructor. This syntax is required for any members that do not have no-argument constructors.