Doing the necessary work before initializing the element in the constructor

I have a design question regarding classes and their constructors in C ++. I come from several years of Java experience. In Java, I would do like this: I have a class to manage SQLite DB as storage. In the constructor of this class, I will pass the path to the application data directory as a parameter. I would then search for the database file, establish a connection, and for example load the most recent table record for caching purposes.

Now my problem is how to do this in C ++. My main problem here is that when execution reaches the first constructor statement, all the members of the class are already initialized, either implicitly or explicitly.

Now my question is, if I had some kind of computation for the constructor parameters before using them to initialize the class members, how would I do that in C ++?

I've already found that I can just use assignment for members in constructors, but I've also read that you shouldn't do that because that would mean that the members are first initialized by their default constructors and then initialized again.

What is the canonical way when you need to do some kind of computation (like loading and parsing a configuration file) before the members of the class can be initialized? I'd rather just provide the path to the constructor and then do the loading and parsing of the element's initialization with the loaded values ​​inside the constructor.

+3


source to share


1 answer


Put the computational part in a separate function:

class C {
  std::string x;
  int y;
  C(int xarg, int yarg);
};

std::string computeX(int xarg, int yarg) {
    ...
  return result;
}

C::C(int xarg, int yarg) : x(computeX(xarg, yarg)), y(yarg) {}

      



As an "initialization" function, you can use a global function, a function defined locally in the source file (for example, in an unnamed namespace), or even call a specific lambda. You can also use a static member function - also if it is a private one - or a member function of one of the arguments.

+6


source







All Articles