Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ calling non-default constructor as member [duplicate]

Tags:

c++

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?

like image 798
clamp Avatar asked Dec 13 '22 19:12

clamp


1 Answers

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);
like image 66
kennytm Avatar answered Feb 13 '23 00:02

kennytm