c++ - Does default constructor have to be provided if there are no meaningful values? -
the default constructor used automatically whenever object default or value initialized. convenient having default constructor.
but if there no meaningful default values class,
- should class still have provide default constructor?
- is there bad influence if no default constructor provided?
for example, person should have name, empty string not meaningful name:
#include <string> class person { public: person() : name("") {} // have supplied? explicit person(const std::string &n) : name(n) {} private: std::string name; };
but if there no meaningful default values class, should class still have provide default constructor?
generally-speaking, no. if objects should not initialised invalid state constructor must provide means creating valid objects, means must take arguments.
you might need provide default constructor:
- if you're using serialization/deserialization framework or other runtime service creates objects , sets fields later (e.g. orm).
- if you're using
std::map
value-type needs default-constructor - if you're creating simple dto objects it's okay object exist in invalid state.
is there bad influence if no default constructor provided?
if mean "no program-defined parameterless constructor", compiler create 1 you, might undesired, must use = delete
modifier ensure compiler not create default constructor.
as case when objects have no default nor parameterless constructor might find containers in stl might not work class.
Comments
Post a Comment