Jaege
Jaege

Reputation: 1863

Does default constructor have to be provided if there are no meaningful values?

The default constructor is used automatically whenever an object is default or value initialized. So it is convenient having a default constructor.

But if there are no meaningful default values for a class,

For example, a person should have a name, an empty string is not a meaningful name:

#include <string>

class Person {
public:
    Person() : name("") {}  // Does it have to be supplied?
    explicit Person(const std::string &n) : name(n) {}
private:
    std::string name;
};

Upvotes: 1

Views: 153

Answers (1)

Dai
Dai

Reputation: 155045

But if there are no meaningful default values for a class, should the class still have to provide a default constructor?

Generally-speaking, no. If your objects should not be initialised into an invalid state then the constructor must provide the means for creating valid objects, which means they must take arguments.

You might need to provide a default constructor:

  • If you're using a serialization/deserialization framework or other runtime service which creates objects by itself and then sets fields later (e.g. an ORM).
  • If you're using std::map the value-type needs a default-constructor
  • If you're creating simple DTO objects where it's okay for the object to exist in an invalid state.

is there any bad influence if no default constructor is provided?

If you mean "no program-defined parameterless constructor", then the compiler will create one for you, this might be undesired, so you must use the = delete modifier to ensure the compiler does not create the default constructor.

As for the case when your objects have no default nor parameterless constructor you might find some containers in the STL might not work with your class.

Upvotes: 2

Related Questions