Search code examples
c++visual-studio-2008operator-overloadingforward-declarationunary-operator

How do I implement a unary operator overload for a forward declared type in C++?


The following code does not compile in Visual Studio 2008. How do I get it to allow a unary operator in the Foo1 class that converts it to a Bar, when Foo1 is defined before Bar?

class Foo1
{
public:
    int val;

    operator struct Bar() const;
};

struct Bar
{
    int val;
};

// This does not compile
Foo1::operator Bar() const
{
    Bar x;
    x.val = val;
    return x;
}

Solution

  • I figured out the answer. There are two solutions:

    struct Bar;
    
    class Foo1
    {
    public:
        int val;
    
        operator struct Bar() const;
    };
    

    Or:

    class Foo1
    {
        typedef struct Bar MyBar;
    public:
        int val;
    
        operator MyBar() const;
    };
    

    (The operator::Bar() implementation remains unchanged)