Constructors can also be overloaded as functions do. For example,
#include <iostream>
class Point
{
int m_x{};
int m_y{};
public:
Point() // default constructor
: m_x{1}, m_y{1}
{
std::cout << "Default constructor Point()\n";
}
Point(int x, int y = 1)
: m_x{x}, m_y{y}
{
std::cout << "Constructor with one default arg y Point(x, y=1)\n";
}
void print() const
{
std::cout << "{" << m_x << ", " << m_y << "}\n";
}
};
int main(int argc, char const *argv[])
{
Point{}.print();
Point{2}.print();
return 0;
}First Point object creation should use default constructor as we are not providing any arguments. Second object creation should use default argument constructor.
Warn
There should only be one default constructor in the class. Constructors with default arguments can cause ambiguation. For example,
Point() {} // default constructor Point(int x=1, int y=2) {} // default arguments constructor // calling Point point{}; // which constructor to use?