I\'m programming a library (so I have complete access to all the mentioned class
ID: 659087 • Letter: I
Question
I'm programming a library (so I have complete access to all the mentioned classes). Two classes (A and B) are essentially the same and differ only by their implementation, so they can be easily converted into each other. But I'm asking myself, if converting by passing an argument of type B to on of A's constructors or by implicitly casting B into A, is better. For a clearer understanding, two code examples:
The casting version:
class A
{
public:
int c[3];
operator B() const
{
//return B(...);
}
};
class B
{
public:
int a, b, c;
operator A() const
{
//return A(...);
}
};
The constructor version:
class A
{
public:
A(const B& b)
{
//...
}
int c[3];
};
class B
{
public:
B(const A& a)
{
//...
}
int a, b, c;
};
Are there any pros/cons to prefer one implementation over the other? Could there be some problems, if someone would extend the library and used the explicit keyword in some of his constructors?
Explanation / Answer
The common way to perform such conversions is through the constructor. The typecast operators are used effectively only for conversions to primitive types (and then mostly to bool or something that effectively acts like a boolean) or types that you can't add an additional constructor to.
The typecast operators have a much bigger risk of being invoked at unexpected moments than converting constructors and should generally be treated with extreme caution.