= default
¶
Problem: Default Constructor Not Automatically Generated¶
Rule: C++ does not generate a default constructor if a constructor has been defined manually
#include <iostream>
using namespace std;
class LackingDefaultConstructor
{
public:
LackingDefaultConstructor(const std::string& s) : _s{s} {}
const std::string& str() const { return _s; }
private:
const std::string _s;
};
int main()
{
LackingDefaultConstructor ldc;
cout << ldc.str() << endl;;
return 0;
}
code/c++11-default-explicit.cpp:15:31: error: no matching function for call to ‘LackingDefaultConstructor::LackingDefaultConstructor()’
15 | LackingDefaultConstructor ldc;
| ^~~
code/c++11-default-explicit.cpp:7:5: note: candidate: ‘LackingDefaultConstructor::LackingDefaultConstructor(const string&)’
7 | LackingDefaultConstructor(const std::string& s) : _s{s} {}
| ^~~~~~~~~~~~~~~~~~~~~~~~~
code/c++11-default-explicit.cpp:7:5: note: candidate expects 1 argument, 0 provided
code/c++11-default-explicit.cpp:4:7: note: candidate: ‘LackingDefaultConstructor::LackingDefaultConstructor(const LackingDefaultConstructor&)’
4 | class LackingDefaultConstructor
| ^~~~~~~~~~~~~~~~~~~~~~~~~
C++ < 11 Solution: Write Default Constructor 😠 👎¶
Write possibly large amounts of code that could have generated by the compiler
Well, a real-life default-ctor implementation might be a bit more complicated than in this example 🙄
#include <iostream>
using namespace std;
class HasDefaultConstructor
{
public:
HasDefaultConstructor() {} // <---- HMPF!
HasDefaultConstructor(const std::string& s) : _s{s} {}
const std::string& str() const { return _s; }
private:
const std::string _s;
};
int main()
{
HasDefaultConstructor hdc;
cout << hdc.str() << endl;;
return 0;
}
C++ >= 11 Solution: = default
¶
#include <iostream>
using namespace std;
class HasDefaultConstructor
{
public:
HasDefaultConstructor() = default;
HasDefaultConstructor(const std::string& s) : _s{s} {}
const std::string& str() const { return _s; }
private:
const std::string _s;
};
int main()
{
HasDefaultConstructor hdc;
cout << hdc.str() << endl;;
return 0;
}