1

I have found the following example in one of my C++ courses. When I try to compile it I get the following error:

'B::operator A' uses undefined class 'A'

Why does it say that class A is undefined?

#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()
{
    B b;
    A a = b;
    cout << a.get_x();
    system("Pause");
}
Shury
  • 468
  • 3
  • 15
  • 49
  • 2
    You can't use that with a forward declaration. Declaration of `A` needs to go before declaration of `B` in this case. Only pointers or references are allowed in your case. – πάντα ῥεῖ Sep 04 '15 at 11:55

2 Answers2

3

The compiler needs to know what A is here:

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

But you only have a forward declaration. You need to move the declaration of class A above B

You are only allowed to use pointers to or references of incomplete types which is what have when you forward declare a type

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
2

You need to declare A above B, so that the definition of A is visible to B.

#include<iostream>
using namespace std;

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


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

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

This should work.

Navneet
  • 4,543
  • 1
  • 19
  • 29