calling constructor of a class member in constructor

shampa picture shampa · Oct 14, 2011 · Viewed 34.4k times · Source

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

Answer

Kerrek SB picture Kerrek SB · Oct 14, 2011

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.