0

I'm having trouble defining and using two codependent classes in a C++/CLI library.

Based off of the answer to this question: Visual C++ (C++/CLI) Forward Declaration with Derivative Classes?

I have this: A.h

#pragma once
#include "B.h"

#ifdef B_H

namespace TestForwardDeclaration
{
    public ref class A
    {
    public:
        A()
        {
        }
        double Result;
        void Test(B ^b)
        {
            this->Result = b->Result;
        }
    };
}

#endif 

B.h

#define B_H

#pragma once

ref class A;
namespace TestForwardDeclaration
{
    public ref class B
    {
    public:
        B()
        {
        }
        double Result;
        void Test(A ^a)
        {
            this->Result = a->Result;
        }
    };
}

#include "A.h"

This compiles and seems to have the functionality that I need, but I'm having trouble correctly implementing in a different file such as the main DLL file. if I include either A.h, B.h, or both, I get the error "use of undefined type 'A'.

What am I missing?

EDIT

I have yet to see a clear and full example of what seems to be a popular problem in C++ (using codependent classes), so here is the solution to my specific use case:

A.h

#pragma once
#include "B.h"

#ifdef B_H

namespace TestForwardDeclaration
{
    public ref class A
    {
    public:
        A();
        double Result;
        void Test(B ^b);
    };
}

#endif 

B.h

#define B_H

#pragma once

namespace TestForwardDeclaration
{
    ref class A;

    public ref class B
    {
    public:
        B();
        double Result;
        void Test(A ^a);
    };
}

#include "A.h"

TestForwardDeclaration.cpp

// This is the main DLL file.

#include "stdafx.h"
#include "A.h"
#include "B.h"
namespace TestForwardDeclaration
{
    A::A()
    {
    }
    void A::Test(B ^b)
    {
        this->Result = b->Result;
    }
    B::B()
    {
    }
    void B::Test(A ^a)
    {
        this->Result = a->Result;
    }
}
mSours
  • 43
  • 8
  • The compiler won't be able to generate code for the Test() function yet, it does not know the definition of A. You can only declare Test(), but not define it. Move the definition into a .cpp file, one that #includes both A.h and B.h. – Hans Passant Jul 20 '18 at 16:08
  • I get, 'class' type redefinition error – mSours Jul 20 '18 at 16:46
  • Do not define the class again, define only the function. And remove the #include from b.h. Google "c++ include guards" while you are at it. – Hans Passant Jul 20 '18 at 16:55
  • That did it. For anyone reading, I also had to move *ref class A;* in B.h inside the namespace TestForwardDeclaration, otherwise there was a signature mismatch when defining the method Test(A ^a) – mSours Jul 20 '18 at 19:18

0 Answers0