C++ Constructors – Constructor vs Casting Operator

cconstructorsexplicittype casting

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 easily be converted into one another.
But I'm asking myself, if converting by passing an argument of type B to one of A's constructors or by implicitly casting B into A, is preferable. Two code examples to illustrate:

Using casting:

class A
{
public:
    int c[3];
    operator B() const
    {
        //return B(...);
    }
};

class B
{
public:
    int a, b, c;
    operator A() const
    {
        //return A(...);
    }
};

Using the constructor:

class A
{
public:
    A(const B& b)
    {
        //...
    }
    int c[3];
};

class B
{
public:
    B(const A& a)
    {
        //...
    }
    int a, b, c;
};

What are the pros and cons of both approaches? Which should one use? And could there be some problems, if someone extended the library and used the explicit keyword in some of his constructors?

Best 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.

Related Topic