Search code examples
c++identifier

visual c++ undeclared identifier


in A.h

#pragma once
include "B.h"
class A {
    B* aPtrToB;
}

in B.h

#pragma once
include "A.h"
class B{
    A* aPtrToA;
}

visual c++ says "error C2065: 'A' : undeclared identifier"

any ideas?

thanks!


Solution

  • You have a cyclic inclusion. The #pragma once is preventing the infinite inclusion that would result from this, but it means that either A won't have the definition of B above it or B won't have the definition of A above it, depending on which ever was compiled first.

    The solution is to not #include the header files, since you only need a forward declaration to declare a pointer:

    #pragma once
    
    class B;
    
    class A {
        B* aPtrToB;
    };
    

    and:

    #pragma once
    
    class A;
    
    class B {
        A* aPtrToA;
    };