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).
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.