Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class Bar { operator Foo(); }

What does this style of operator overloading mean?

class Foo {
    Foo(int a) { ... }
};

class Bar {
    operator Foo() { return Foo(25); }
};
like image 958
cached Avatar asked Sep 23 '26 10:09

cached


1 Answers

That is user-defined conversion function which converts an instance of Bar into Foo implicitly.

Bar bar;

Foo foo = bar;  // bar implicitly converts into Foo.

It is as if you've written this:

Foo foo = Foo(25);

If you've such a conversion function, then you can call this:

void f(Foo foo); //a function which accepts Foo

f(bar); // bar implicitly converts into Foo.

So such implicit conversion may not be desirable sometime, as it might cause problem, producing unintended result. To avoid that, you can make the conversion function explicit as (in C++11 only):

//valid in C++11 only

class Bar {
  explicit  operator Foo() { return Foo(25); }
};

Now both of these would give error:

Foo foo = bar; //error
f(bar); //error

However, the following is allowed:

Foo foo = static_cast<Foo>(bar); //Ok
f(static_cast<Foo>(bar)); //Ok
like image 159
Nawaz Avatar answered Sep 26 '26 10:09

Nawaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!