Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ambiguous constructor call while object creation

My program is as follows:

class xxx{
       public: explicit xxx(int v){cout<<"explicit constructor called"<<endl;}
               xxx(int v,int n=0){cout<<"default constructor called"<<endl;}
  };
  int main(int argc, char *argv[])
  {
   xxx x1(20);    //should call the explicit constructor
   xxx x2(10,20); //should call the constructor with two variables
   return 0;
  }

When I compile I get the error:- "call of overloaded âxxx(int)â is ambiguous"

I know that compiler finds both constructor signature equal since I made an argument by default '0'.

Is there any way that compiler can treat the signatures different and the program would compile successfully?

like image 958
Santosh Sahu Avatar asked May 03 '26 13:05

Santosh Sahu


2 Answers

You just need one constructor

class xxx
{
public:
    explicit xxx(int v, int n=0)
    {
       cout << "default constructor called" << endl;
    }
};

Then you could initialize XXX objects:

xxx x1(20);    //should call the explicit constructor
xxx x2(10,20); //should call the construct
like image 55
billz Avatar answered May 05 '26 02:05

billz


You have 2 choices:

Remove one of the constructors:

class xxx
{
public:
    explicit xxx(int v, int n = 0); // don't forget explicit here
};

Remove the default parameter:

class xxx
{
public:
    explicit xxx(int v);
    xxx(int v,int n);
};

Either way the code in main() will work. The choice is yours (and is mostly a matter of a subjective taste).

like image 39
Sergey K. Avatar answered May 05 '26 01:05

Sergey K.