Reputation: 496
How is the conversion operator defined in class B is working in the following code? I read all other articles related to conversion operators on stack overflow but couldn't find any explanation for the interconversion of objects of two different classes. Any help would be much appreciated as I am new to c++
For the following code:
#include<iostream>
using namespace std;
class A
{
int i;
public:
A(int ii = 0) : i(ii) {}
void show() { cout << i << endl; }
};
class B
{
int x;
public:
B(int xx) : x(xx) {}
operator A() const { return A(x); }
};
void g(A a)
{
a.show();
}
int main()
{
B b(10);
g(b);
g(20);
return 0;
}
I am unable to understand how the conversion operator is working and how the value is getting assigned to A's object. Basically I am unable to understand the flow of code and I want to know behind the scenes i.e how the conversion is taking place?
Upvotes: 1
Views: 346
Reputation: 21576
In C++, there is such a thing known as Implicit Conversion Sequences during overload resolution. This kicks in all the time in other to select the best viable function to call.
For the case of:
void g(A a)
{
a.show();
}
int main()
{
B b(10);
g(b);
...
}
You have a User defined conversion sequence there. Since there is no function overload of g
that takes in any CV type of b
, A Conversion Sequence will be up for ranking. It turns out that A
can be constructed from B
due the conversion operator in B
. This is used.
Hence the conversion function (operator) in B
will be invoked to produce A
which is used to initialize the argument in g
For the case of:
void g(A a)
{
a.show();
}
int main()
{
B b(10);
g(23);
...
}
You have a converting constructor that is able to construct an object of type A
from an int
Upvotes: 1
Reputation: 4991
Here's what's going on :
b
(type: B
)g
passing b
as its parameterb
is of type B
, g
expects a variable of type A
, g
looks for a way to convert from B
to A
A
and B
are classes, B
overloads the "conversion operator" operator A()
g
is automatically converted to b.operatorA()
which returns an A
g
is executed with a
being b.operatorA()
g
calls the method show
on a
g
Upvotes: 2
Reputation: 45434
The compiler must somehow work out what to do with your g(b)
. The only available candidate is void g(A)
, so it checks whether it can use that. If there exist a way to legally convert the argument (b
) to an A
then that is a possibility. Since B
has a corresponding conversion operator, this is indeed the case. In fact, it's the only possibility. So, de facto the call g(b)
becomes equivalent to
g(static_cast<A>(b));
which explicitly calls the conversion operator.
Upvotes: 0