'error: member access into incomplete type''; note: forward declaration of ''

Here is a struct MAIN which have member struct A and struct B, the code is like below

// a.hpp
#ifndef _A_HPP_
#define _A_HPP_
struct A
{
    int mem1;
};
#endif
// b.hpp
#ifndef _B_HPP_
#define _B_HPP_

#include "a.hpp"
#include "main.hpp"
struct MAIN;
struct A;

struct B{
    int mem2;
    MAIN* main;
    A *aptr;
    B(){
        *aptr=this->main->a;
    }
};


#endif
// main.hpp
#ifndef _MAIN_HPP_
#define _MAIN_HPP_

#include "a.hpp"
#include "b.hpp"

struct MAIN{
    A a;
    B b;
};

#endif
// main.cpp
#include "main.hpp"
int main(){
    MAIN m;
    return 0;
}

I'd like to use the aptr in struct B to visit A which in the same MAIN, but compile error like

In file included from main.cpp:2:
In file included from ./main.hpp:6:
./b.hpp:15:25: error: member access into incomplete type 'MAIN'
        *aptr=this->main->a;
                        ^
./b.hpp:7:8: note: forward declaration of 'MAIN'
struct MAIN;
       ^
1 error generated.

How the error occured? my code should use struct but not class, and hpp but not h with cpp. Is there anyway to fix it? Hope for help



Solution 1:[1]

The definition of the constructor B::B inside the struct definition references members of MAIN, but the latter hasn't been fully defined yet.

You need to move the body of constructor B::B into a separate file, i.e. b.cpp, and link with main.cpp when building the executable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dbush