For two unrelated classes “class A” and “class B”
and a function
B convert(const A&);
Is there a way to tell C++ to automatically, for any function that takes “class B” as argument, to auto convert a “class A”.
Thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What you would normally do in this case is give
Ba constructor that takes anA:And do the conversion there. The compiler will say “How can I make
AaB? Oh, I seeBcan be constructed from anA“.Another method is to use a conversion operator:
And the compiler will say “How can I make
AaB? Oh, I seeAcan be converted toB“.Keep in mind these are very easy to abuse. Make sure it really makes sense for these two types to implicitly convert to each other.