Why is my overloaded member function only "ambiguous" as a char and not an int and string?
I'm trying to create a one-code path for my Char class by funneling code through an overloaded equals() function. It works fine when I use equals as an int and string but is ambiguous as a char.
class Char
{
private:
char cData;
int iData;
string sData;
public:
//Mutators:
void equals(char c);
void equals(int c);
void equals(string c);
//Constructors:
Char(char c);
Char(int c);
Char(string c);
};
void Char::equals(char c)
{
cData = c;
}
void Char::equals(int c)
{
iData = c;
}
void Char::equals(string c)
{
sData = c;
}
Char::Char(char c)
{
this->equals(c); //Call to member function 'equals' is ambiguous
}
Char::Char(int c)
{
this->equals(c);
}
Char::Char(string c)
{
this->equals(c);
}
The error only happens for char, which is confusing since string works fine. I expected it to work for all of them since that's been the case so far.
It's ambiguous because if you do
Char c(42);
The compiler does not know whether it should call the char
or int
constructor. Both are an equally good match.
The same goes for equals(123);
. Again, both the char
and int
overloads match and the compiler cannot tell which one you intend to call.