c++typedefforward-declarationunnamed-class

Forward declaration of anonymous typedef with bitfields in C++


I found an answer for a forward declaration of a typedef in C++ (https://stackoverflow.com/a/2095798). But my situation looks like this:

// a.h
 typedef struct{
    unsigned char bah0 : 1;
    unsigned char bah1 : 1;
    unsigned char bah2 : 1;
    unsigned char bah3 : 1;
    unsigned char bah4 : 1;
    unsigned char bah5 : 1;
    unsigned char bah6 : 1;
    unsigned char bah7 : 1;
 } bah;

// b.h
typedef struct bah;  // Error: using typedef-name 'bah' after struct

 class foo {
   foo(bah b);
   bah mBah;
 };

// b.cpp
 #include "b.h"
 #include "a.h"

 foo::foo(bah b) 
 {
   mBah = b;
 }

and I am not allowd to change anything in a.h and I want to avoid including a.h in b.h. How can I avoid this error or what is the right way to forward declarte bah in this situation?

Thany you! Zlatan


Solution

  • I want to avoid including a.h in b.h

    Too bad. b.h depends on the definition of bah from a.h. Your wants are at odds with the rules of the language.

    How can I avoid this error

    Option 1: Include a.h in b.h. I know you don't want this, but I want to include all options that are available.

    Option 2: Don't depend on definitions of a.h in b.h. An example:

    // b.h
    class foo {
        foo();
    };
    

    A following class could be defined with only a forward declaration of bah:

    class foo {
        foo(bah* b);
        bah* mBah;
    };
    

    However, even this is not possible unless you can forward declare the structure. So this brings us to...

    what is the right way to forward declarte bah in this situation?

    There is no way to forward declare an unnamed struct. Unless you can modify a.h, you cannot give a tag name for the struct. Assuming that you could change a.h, this is how you would do it:

    typedef struct bah { // struct now has the tag name bah
        // ...
    } bah;
    

    Since the name of the struct makes the typedef mostly redundant, you could simplify to:

     struct bah {
        // ...
     };
    

    After this addition, you can forward declare:

    struct bah;
    

    But forward declaration won't allow you to declare variables of type bah.


    PS. Bit fields have no effect on how forward declarations work.