Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a class's default constructor whose one is provided by a ctor with all default paramters?

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.

like image 630
Maestro Avatar asked Dec 03 '22 10:12

Maestro


2 Answers

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
}
like image 124
eerorika Avatar answered Dec 20 '22 10:12

eerorika


If you add a constructor that defaults all parameters, it is the default constructor.

If you want both, remove one or more of the default arguments.

like image 34
Sid S Avatar answered Dec 20 '22 09:12

Sid S