Captain_Tiras Captain_Tiras - 13 days ago 5
C++ Question

Initialize object data members C++

Consider the following code:

class Game {
private:
vector<SomeType*> vec;
OtherType obj;

public:
Game(char* configuration_file);
};


How should one implement the Game constructor considering that both vec and obj are dependent on configuration_file content?

Initialization list is impossible to use since configuration_file has to be parsed before constructing vec and obj.

If i will constrcut vec and obj inside the body of the constructor, than both default constructors for both of them will be called, is there a way to prevent this ?

What is the normal way to do this kind of things ?

Thanks.

Answer

Default-constructing the vector is certainly harmless, so let's assume that default-constructing OtherType is impossible. Then I'd handle it this way:

class Game {
private:
  vector<SomeType*> vec;
  OtherType obj;

  static OtherType load(const char* config_file);

public:
  Game(const char* config_file)
    : obj(load(config_file))
  {
    // populate vec here
  }
};
Comments