-1

I have two errors : return type 'class A' is incomplete and conversion from 'B' to non-scalar type 'A' requested. I'm not sure what I am doing wrong because I am not very good on writing classes in C++. Any help would be appreciated! Thanks.
This is the code :

#include <iostream>

using namespace std;
class A;
class B
{
    int x;
    public: B(int i=10) {x=i;}
    operator A();
};
B::operator A() {return x;}
class A
{
    int x;
    public:A(int i=7) {x=i;}
    int get_x() {return x;}
};
int main()
{
    B b;
    A a=b;
    cout<<a.get_x();
    return 0;
}
locket23
  • 71
  • 1
  • 1
  • 7

1 Answers1

1

Class A needs to be fully defined before you can return it from the conversion operator (operator A();), which returns an instance of A by value. The fact that is returns it by value is key here, as this requires a type to be fully defined beforehand.

Your code would look like this:

#include <iostream>

using namespace std;

class A
{
    int x;
    public:A(int i=7) {x=i;}
    int get_x() {return x;}
};

class B
{
    int x;
    public: B(int i=10) {x=i;}
    operator A();
};

B::operator A() {return x;}

int main()
{
    B b;
    A a=b;
    cout<<a.get_x();
    return 0;
}

The corresponding output is:

10

Verified with Coliru.

Peter K
  • 1,372
  • 8
  • 24