views:

83

answers:

5

There are two classes: A and B. There are algorithms for converting from type A to type B and back. We cannot touch the source code of them. Can I write an implicit conversion between the two types?

Example code which should work:

B CalculateSomething(double x)
{
    A a(x);
    a.DoSomethingComplicated();
    return a;
}
A: 

There are two classes: A and B. There are algorithms for converting from type A to type B and back. We cannot touch the source code of them. Can I write an implicit conversion between the two types?

No, if A and B aren't related you can't. (And I am grateful for that. Implicit conversions give enough headaches as they are without the ability to create them for 3rd-party classes.)

sbi
A: 

Not possible without altering class definition

hype
+2  A: 

No, I don't think so. Implicit conversion is usually coded with an overloaded operator. It is done for base types too. As you can't modify A and B code there is no way to tell the compiler how to do that. Your snippet will get an error.

You have to do explicit conversion. Just

return helper.convertToB(a);

my2c

neuro
"Implicit conversion is usually coded with an overloaded operator." Or using an implicit constructor. I'd prefer the latter, although I have learned the hard way to shy away from any implicit conversions.
sbi
@sbi : I agree. I ALWAYS prefer EXPLICIT conversion. Ah, readability and ease of maintenance, why are you so much underestimated ...
neuro
+2  A: 

No, but you can write a named free function to do it.

B ToB( const A & a ) {
   B b;
   // process a somehow to add its data  to b
   return b;
}

Your code then becomes:

B CalculateSomething(double x)
{
    A a(x);
    a.DoSomethingComplicated();
    return ToB( a );
}

which is arguably clearer than the implicit conversion would be.

anon
A: 

Even if you can't change the implementation of A or B, you could add an inline constructor to the definition of B that takes a const A&.

I would suspect however that unless the classes really are closely related it would be better to provide an explicit conversion function - implicit conversions can be a huge source of difficult-to-find bugs:

B CalculateSomething(double x)
{
    A a(x);
    a.DoSomethingComplicated();
    return ConvertAToB( a );
}
Bids
hype
You are not talking about modifying 3rd-party headers, do you? Otherwise you are going to get some nice shiny binary incompatibility.
Vlad
You shouldn't get any binary incompatibility if you do not change the vtable of the class (i.e. don't add any virtual methods). This isn't a nice solution, it is the only solution if (for whatever reason) you really need the implicit conversion.As I said in the second part of my answer, implicit conversions are generally bad - my recommendation (as others have stated) would be an explicit conversion method or helper.
Bids