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;
}
A default constructor is a 0 argument constructor which contains a no-argument call to the super class constructor. To assign default values to the newly created objects is the main responsibility of default constructor.
Like all functions, a constructor can have default arguments. They are used to initialize member objects. If default values are supplied, the trailing arguments can be omitted in the expression list of the constructor.
ambiguous means the compiler found multiple “valid” choices and refused to make the choice for you. You need to add clarifying information (usually about types). It may be that the compiler is able to convert a value into a type that matches a constructor and can do this twice.
Constructor Overloading in C++ In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With