If I have 2 classes A
and B
and wish to implement conversion from A
to B
, I can see 2 possibilities.
1st possibility
class A {
// Some attributes, methods
operator B() const {
// Conversion from A to B
}
}
class B {
// Some attributes, methods
}
2nd possibility
class A {
// Some attributes, methods
}
class B {
// Some attributes, methods
B& operator =(const A& src) {
// Conversion from A to B
}
}
Both these methods allow to run the following code:
Executed code
A instA;
B instB;
instB = instA; // Ok
Now let's imagine I implement both functions (cast to B
in class A
and operator =
from A
in class B
:
3rd possibility
class A {
// Some attributes, methods
operator B() const {
// Conversion from A to B - Code 1
}
}
class B {
// Some attributes, methods
B& operator =(const A& src) {
// Conversion from A to B - Code 2
}
}
assuming Code 1 and Code 2 have the same effect (or even different effects, why not).
My questions are:
- If competing cast/assignment methods are provided, which one would be chosen first when doing implicit cast?
- Is there any interest implementing both competing cast/assignment methods?
- Perhaps this would even be a good idea to call
operator =
of classB
inB()
cast operator of classA
?