1

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.

3
  • why not copy construct it directly obj = OtherType(parsedData); in the constructors body. if you make the default constructor private, it will not compile Commented Nov 20, 2016 at 2:15
  • from my understanding that will cause a call to obj default constructor since all Game data members have to be initialized before entering the body, i would like to save that call. Commented Nov 20, 2016 at 2:21
  • yes, before entering the body constructor, all default constructor of objects will be called. john zwick solution is good Commented Nov 20, 2016 at 2:26

2 Answers 2

1

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
  }
};
Sign up to request clarification or add additional context in comments.

1 Comment

@Captain_Tiras: That would be one way, or you could just implement load().
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.