Search code examples
c++type-conversionincomplete-type

class type conversion fails C++


I'm trying to make something compile, but it won't, and I couldn't find anything relevant on the web.

#include<iostream>
using namespace std;

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

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

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

I get the errors: return type 'class A' is incomplete conversion from 'A' to non-scalar type 'B' requested

Not even this works:

    B B;
    A a=b;

I don't know what I do wrong, and I don't know where to find more info on the subject.

Thank you


Solution

  • You didn't post the full text of your errors, which means you left out the all important line numbers. As is often the case, the line numbers are often the most valuable piece of information in an error.

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

    I'm guessing that this is the line your compiler is telling you the error occurs on.

    At this line of code, the compiler does not yet have a complete declaration of A so it has no idea how to convert int x into class A. C++ compilation is single pass, so it can't defer this lookup.

    You need to complete your declarations before you proceed to the definitions.

    class A;
    class B
    {
        int x;
    public:
        B(int i=107) {x=i;}
        operator A();
    };
    
    class A
    {
        int x;
    public:
        A(int i=6) {x=i;}
        int get_x() {return x;}
    };
    
    // done with declarations. begin definitions.
    
    B::operator A() {return x;}
    // compiler quietly expands this to be:
    // B::operator A() { return A::A(i=this->x); }
    

    Typically A and B would be in header files and you would keep the definition, which requires both classes to be fully declared, for a .cpp file somewhere.