Consider the sample code below:
#include <iostream>
using namespace std;
class dummy
{
private:
int y;
public:
dummy(int b = 0) : y(b) {
}
friend ostream& operator<<(ostream& os, const dummy& obj);
};
ostream& operator<<(ostream& os, const dummy& obj)
{
os << obj.y;
return os;
}
class sample
{
private:
int x;
public:
sample(int a = 0) : x(a)
{
}
operator dummy()
{
dummy d(100);
return d;
}
operator int()
{
return x;
}
};
int main()
{
sample ob1(5);
dummy d;
//d = ob1; //Line1
d = (dummy)ob1; //Line2
cout << d << "\n";
}
In Line1, an implicit cast is done. I understand how the implicit casting works in this case. The compiler gives no errors.
But in Line2, an explicit cast of sample
object is done to dummy
object. But the compiler gives the following error.
error: call of overloaded `dummy(sample&)' is ambiguous
note: candidates are: dummy::dummy(const dummy&)
note: dummy::dummy(int)
Questions:
Why is these errors occurring?
I do not understand the meaning of the error messages. Why the candidate functions of
dummy
class mentioned in the errors?