Search code examples
c++default-constructor

How to "default constructor" in C++


There's a problem I've been running into lately and since I'm a self taught C++ programer I'd really like to know how professionals in the real world solve it.

Is it a good idea to write a default constructor for all classes? Aren't there certain parts of the STL that won't work if your classes don't have default constructors?

IF SO, then how does one write a default constructor that does sensible things? That is, how can I assign default values to my private members if there simply are not sensible default values? I can only think of two solutions:

  1. Use pointers (or unique_ptrs) for each member and that way a nullptr means the field is uninitialized.

OR

  1. Add extra fields/logic/methods to do the work of checking to see whether or not a field has been initialized and rely on that (think kind of like unique_ptr's "reset" method).

How do people solve problems like this in the real world?


Solution

  • If it doesn't make sense for your data type to have a default constructor, then don't write one.

    (STL is long dead, but I assume you mean the standard library.) Most standard library containers work well even if the contained type doesn't have a default constructor. Some notable gotchas:

    • std::vector<T>::resize(n) requires T to have a default constructor. But without one, you can use erase and insert instead.

    • std::map<K,V>::operator[] and std::unordered_map<K,V>::operator[] require V to have a default constructor. But without one, you can use find and insert instead.