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

Suppose I have a class A without a default constructor, a factory method factoryA that returns an object of type A, and a class B that has A as its member. I know that in this case the member of type A of B has to be initialize in B's constructor initialization list. It is not entirely clear to me why so if someone could explain that to me it would be great. Also, what if the parameter to A's constructor needs to be computed inside of B's constructor, say by querying a database or something of that nature? Is there a way to use the setup below without providing A with a default constructor? Thanks in advance.

class A {
private:
  int _i;
public:
  A(int i) : _i(i) {} 
};

A factoryA(bool b) {
  if(b)
    return A(1);
  else return A(2);
}

class B {
private:
  A _a;
public:
  B(int j) {
    if(j > 0)
      _a = factoryA(true);
    else _a = factoryA(false);
  }
};
See Question&Answers more detail:os

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

1 Answer

Member objects are always initialized before entry into the body (the part between the curly braces) of the constructor. If you don't mention a member in the initializer list, it gets default constructed. So mention it!

B::B(int j) : _a(factoryA(0 < j)) { };

This calls the function factoryA with the argument value true if j is greater than 0 and false otherwise, and initializes the member _a with the value returned by that call.


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