Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ auto conversions

Tags:

c++

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!

like image 470
anon Avatar asked Feb 07 '10 07:02

anon


1 Answers

What you would normally do in this case is give B a constructor that takes an A:

class B
{
public:
    B(const A&);
};

And do the conversion there. The compiler will say "How can I make A a B? Oh, I see B can be constructed from an A".

Another method is to use a conversion operator:

class A
{
public:
    operator B(void) const; 
}

And the compiler will say "How can I make A a B? Oh, I see A can be converted to B".

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.

like image 89
GManNickG Avatar answered Oct 01 '22 18:10

GManNickG