Philip L
Philip L

Reputation: 359

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.

Upvotes: 1

Views: 76

Answers (2)

John Zwinck
John Zwinck

Reputation: 249123

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
  }
};

Upvotes: 1

Sam Varshavchik
Sam Varshavchik

Reputation: 118300

Sometimes, one has to take a slight detour in order to get where one's going.

First, write a static private function:

std::pair<std::vector<SomeType *>, OtherType> Game::parse_config_file(char *configuration_file)
{
  // ...
}

This would be a private static function that parses the configuration file into this kind of data.

Now, you can put this jigsaw puzzle together:

class Game_config {

protected:

  vector<SomeType*> vec;
  OtherType obj;

  Game_config(const std::pair<std::vector<SomeType *>, OtherType> &);
};

class Game : private Game_config {

    static std::pair<std::vector<SomeType *>, OtherType> Game::parse_config_file(char *configuration_file);

public:
  Game(char* configuration_file) : Game_config(parse_config_file())
  {
  }
};

Game_config's constructor should be obvious.

A slight variation of the above would be to have parse_config_file() return the Game_config superclass, and have Game's constructor copy-construct its superclass. A modern compiler should be able to use RVO, in this use case.

Upvotes: 0

Related Questions