0

I have an object that is created in a .h file that should be initialised in the constructor. This object is passed a COM port number that is 5 in our current application. For this reason I have created a const int in the .h file.

Edit: I added a more complete example

class ClassB
{
public:
    ClassB(int comPort);
private:
    int m_comPort;
};

ClassB::ClassB(int comPort) :
    m_comPort(comPort)
{
}

class ClassA
{
public:
    ClassA();
private:
    const int comPort;
    ClassB B;
};

ClassA::ClassA() :
    comPort(5),
    B(comPort)
{
}

int main()
{
    ClassA A;
    return 0;
}

Because the object is initialised before comPort is fully initialised, the value for comPort is garbage.

What would be the correct way to circumvent this? I can think of the following:

  • Initialise the const int in the header file
  • Create and initialise the object in the body of the constructor
  • use a #define

2 Answers2

1

It seems like a problem with the order your members are initialized. Class members are initialized in the order they are declared. The order they are initialized in the constructor does not override this. In the next example bar::my_foo is initialized before bar::my_const, which will cause problems. my_foo will be initialized with an unitialized my_const member;

struct foo {
    foo(int p_x) : x(p_x) {}
    int x;
}

struct bar {
    bar() : my_const(5), my_foo(my_const) {}
    foo my_foo;
    const int my_const;
}

The problem can be fixed by changing order the members are declared.

struct bar {
    bar() : my_const(5), my_foo(my_const) {}
    const int my_const; // my_const before my_foo
    foo my_foo;
}
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • A less brittle approach would be to not rely on the order at all. `bar(const int var = 5) : my_const(var), my_foo(var) {}` gets rid of any dependency. – NathanOliver Jan 16 '17 at 16:18
0

You can reproduce your error if you exchange declaration of comPort and B in definition of ClassA. See this comment on SO concerning Constructor initialization-list evaluation order.

Hence, make sure that if an initializer list relies on a specific order of evaluation, then the declaration of the members to be initialized must adhere to this order.

Community
  • 1
  • 1
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58