4

let's say i have a class A and a class B. B is used as a member in A. B does not have a default constructor but one that requires a parameter.

class B {
  B(int i) {}
};


class A {

 B m_B;

 A()
 {
    m_B(17); //this gives an error
 }

};

how can i still use B as a member in A?

clamp
  • 33,000
  • 75
  • 203
  • 299

1 Answers1

13

Use initialization list.

class B {
  public:
    B(int i) {}
};

class A {
    B m_B;
  public:
    A() : m_B(17) {}
};

BTW, to reset m_B somewhere outside of the constructor, the correct syntax is:

m_B = B(17);
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • In this example, if that last line `m_B = B(17)` were called from the `A()` constructor, does `B`'s default constructor still get invoked? If so, is there a way to prevent this? – Steven Lu Mar 22 '11 at 05:43
  • @Steven: (1) Yes. (2) Use the initialization list to initialize `m_B`. – kennytm Mar 22 '11 at 05:46