0

I have a class Foo that is initialized with a filename or null. If there is a filename, the object db is initialized, otherwise it is null. Either way, the object db_mon is initialized with the value of db, null or not.

Is this valid:

class Foo {
   Database *db;
   Database_monitor db_mon;

 public: 
   Foo(const char *db_file) : 
      db(db_file ? new db(db_file) : 0), db_mon(db)  {}
};
CaptainCodeman
  • 1,951
  • 2
  • 20
  • 33
  • Initialization happens in the order the member variables are declared, so this seems fine to me. (My compiler even gives a warning if the order in the ctor initializer list does not match the order of declaration.) – Thomas Apr 16 '22 at 12:27
  • Except for the typo `public` -> `public:`, this is valid. However I question the use of a pointer for an optional value. Prefer `std::optional`. – HolyBlackCat Apr 16 '22 at 12:27
  • Or at least `std::unique_ptr` if it has to be a pointer. Also, you probably should delete, or implement with proper semantics, the copy and move operations if the class is self-referential like this. – user17732522 Apr 16 '22 at 12:33

0 Answers0