0

I'm trying to create two classes and access information between the two. This should illustrate the problem that im facing.

main.cpp

#include <iostream>
    
#include "A.h"
#include "B.h"
    
    
int main()
{
    A a = A();
    B b = B();
    a.setB(&b);
    b.setA(&a);
    return 0;
}

A.h

#include "B.h"

struct B;

struct A
{
    B* b;
    int fps = 60;
    
    A() {}

    void setB(B* _b) {
        b = _b;
        std::cout << b->var;
    }
};

B.h

#include "A.h"

struct A;

struct B
{
    A* a;
    int var = 5;

    B() {}

    void setA(A* _a) {  
        a = _a;
        std::cout << a->fps;
    }
};

The error I'm getting is: C2027 use of undefined type "A"

Usitha Indeewara
  • 870
  • 3
  • 10
  • 21
  • 3
    You are recursively include one header in another. – Vlad from Moscow Oct 11 '22 at 12:35
  • 2
    You have a circular dependency. This design is broken. – Cory Kramer Oct 11 '22 at 12:35
  • 2
    You need to move `A::setB` (or `B::setA`) definition after definition of both classes (.cpp would be a good place). – Jarod42 Oct 11 '22 at 12:37
  • As others have mentioned that this is a circular dependency issue. You should go through this answer (https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes) to better understand this issue – Saad_Khan Oct 11 '22 at 12:38
  • 1
    This doesn't address the question, but adding [header guards](https://www.learncpp.com/cpp-tutorial/header-guards/) is a good practice for avoiding the duplicate definition problem. – Usitha Indeewara Oct 11 '22 at 12:53

0 Answers0