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