Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
123 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...