Ashwyn Ashwyn - 1 month ago 11
C++ Question

How to handle the ambiguity between default constructor and overloaded constructor?

The line A b(3) produces ambiguity as it could invoke any of the two possible constructors. Either the single argument parametrized constructor or the two-argument parametrized constructor with default argument. How do i solve this?

#include<iostream>
using namespace std;
class A
{
public:
int a,b;
A()
{
a=5;
b=6;
}
A(int a1)
{
a=a1;
b=54;
}
A(int a1,int b2=8)
{
a=a1;
b=b2;
}
void show()
{
cout<<"a="<<a<<" b="<<b<<endl;
}
};
int main()
{
A a(3); // I want A(int a1,int b2=8) to get executed
A b(3); // I want A(int a1) to get executed
a.show();
b.show();
return 0;
}

Answer

First, answer this:

When you write A a(4), do you want a.b. to be:

Option a) 54

class A
{
    public:
    int a,b;
    A()
    {
        a=5;
        b=6;
    }
    A(int a1,int b2 = 54)
    {
        a=a1;
        b=b2;
    }
};    

Option b) 8

class A
{
    public:
    int a,b;
    A()
    {
        a=5;
        b=6;
    }
    A(int a1,int b2 = 8)
    {
        a=a1;
        b=b2;
    }
};    

The error is there for a reason. If you don't know what you want from the code, how can you expect the compiler to?

EDIT: After your edit - impossible. Not with that exact code.

Comments