Implicit default constructor is only generated when class does not have any constructor. There are cases when the class has constructors and we want to have implicit default constructor. We can achieve this by using = default syntax. For example,
#include <iostream>
class Point
{
int m_x{};
int m_y{};
public:
Point() = default;
Point(int x, int y)
: m_x{x}, m_y{y}
{
std::cout << "Constructing using Point(" << x << ", " << y << ")\n";
}
void print() const
{
std::cout << "{" << m_x << ", " << m_y << "}\n";
}
};
int main(int argc, char const *argv[])
{
Point{}.print();
Point{1, 2}.print();
return 0;
}How is this different from user defined default constructors?
Default constructors either implicitly generated or explicitly using = default do does zero initialization first and then default initialization, when value-initialized. User defined default constructors do default initialization. For example, there are three classes:
- Class
Athat has user define default constructor and one data member asint value;. When class is value initializedA{},valuewill be default initialized to some garbage value. - Class
BandCwhich have implicit and explicit default constructors respectively. If they have one data member defined asint value;and when value initializing the class object,valuewould be zero initialized.