Is it fine to make a default constructor unusable?
https://softwareengineering.stackexchange.com/questions/233807
-
03-10-2020 - |
Question
Specifically asking about the default constructor
Given that the constructor initializes all the data for an object, if I create a class that can't be used without proper initialization, is it not the case that the default constructor is useless? Consider:
// A class for handling lines in a CSV file
class CSV_Entry {
private:
unsigned num_entries;
std::string string_version;
std::vector<std::string> vector_version;
...etc
public:
CSV_Entry();
CSV_Entry(const std::string& src_line);
// returns a vector copy of the original entry
std::vector<std::string> get_vector_snapshot();
}
int main( void ) {
...etc
CSV_Entry example = CSV_Entry();
std::vector<std::string> current_entry = example.get_vector_snapshot();
...etc
}
That variable current_entry
is essentially useless no? If someone tries to process it later on, they would likely get errors; then they'd create code to handle such errors...
To mitigate such additional, unnecessary code: why not make the default constructor unusable? Like so,
...etc
CSV_Entry() {
throw Verbose_Exception( "CSV_Entry: do not use the default constructor" );
}
...etc
PS: on a side note, if it is fine to just make the default constructor unusable, is it fine to put that throw in the header, since no other implementation details are revealed anyway?
Solution
Yes, it's fine (actually, it's good) to make the default constructor unusable if there's no sensible way to initialize the object without any arguments. But don't "disable" it by throwing an exception. Make it private instead. Ideally your interface won't contain any methods or constructors people "aren't supposed to" call.