It is said in C++ primer 5Th edition that a constructor that provides default arguments for all the parameters defines also default constructor:
class Point {
public:
//Point(); // no need to define it here.
Point(int x = 0, int y = 0) : x_(x), y_(y){
std::cout << "Point(int=0, int=0)" << std::endl;
} // synthesize default constructor Point()
int x_;
int y_;
};
int main(){
Point pt; // default ctor Point() or Point(int, int)?
Point pt2 = Point(); // this won't compile?!
}
As you can see above I wanted for some reason to invoke the default constructor Point()
not Point(int, int)
but I get the latter not the default ctor?!
So is it possible to invoke the default constructor of a class provided by a constructor that provides default arguments for all the parameters? Thank you.
A class can have at most one default constructor. If the constructor that has argument is a default constructor, then there may not be a default constructor that does not take arguments. Otherwise invocation of the default constructor is ambiguous.
So is it possible to invoke the default constructor of a class provided by a constructor that provides default arguments for all the parameters?
Well, yes. In that case the default constructor is the constructor that provides default arguments for all parameters. Example:
class Point {
public:
Point(int x = 0, int y = 0);
};
int main(){
Point pt; // the default constructor Point(int,int) is invoked
}