0

Is it a good idea to connect to the database (sqlite) at the constructor of the class, that will hold database handler when daemon(service) running? I'm feeling that it's bad idea, but does not know why.. Or it's ok?

edit: and what to do if I will got the error when open connection.

abrahab
  • 2,430
  • 9
  • 39
  • 64
  • Have a look at how [a bunch of other C++ wrappers](http://stackoverflow.com/questions/120295/what-is-a-good-oo-c-wrapper-for-sqlite) implement this. – CL. Aug 11 '14 at 06:49

2 Answers2

2

It is OK as long as your destructor releases the database, and it's made clear to the user that uses the class that this uses a DB connection (so they don't create thousands of such objects)

If you can't connect, one solution is to throw an exception - it really depends on what you expect the "caller" to do in such a case.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • Throwing an exception is the *only* way to prevent creating an object. Any other error handling mechanism would require to clean up the object by hand. – CL. Aug 11 '14 at 06:45
1

It could be bad if the connection to the database needs to use some global variable, and you create a global object... correct order in global initialization might be tricky.

Best solution, in my opinion, is to open the connection at first usage.

Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64