operator overloading

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;
class A
{
    int i;
public:
    A(int ii = 0) : i(ii) {}
    void show() {  cout << i << endl;  }
};

class B
{
    int x;
public:
    B(int xx) : x(xx) {}
    operator A() const {  return A(x); }
};

void g(A a)
{
    a.show();
}

int main()
{
    B b(10);
    g(b);
    g(20);
    return 0;
}


What type of overloading is this?

Specifically what is operator A() const { return A(x); }? How does it work? Where is return type?

I understand how g(20) works, i.e. conversion constructor.
Last edited on
B::operator A() const { return A(x); } is a user-defined conversion function from B to A.

http://en.cppreference.com/w/cpp/language/cast_operator

The return type is A (it's between the keyword "operator" and the opening parenthesis of the parameter list.
Topic archived. No new replies allowed.