Search code examples
c++structtypedef

typedef struct with no definition


I'm looking at the headers of a C++ library I use and there's a line like this:

typedef struct asdf_t asdf_t;

There is no definition of asdf_t anywhere in the source. What is this line doing?


Solution

  • This is what's know as declaring an Opaque Structure! There are probably functions and/or classes in that header which use pointers to the asdf_t type - which is allowed in C++ for 'undefined' structures. However, there won't (can't) be variables, class members or function arguments declared that are instances of asdf_t.

    So, for example, your header may later declare the following class:

    class GoodBoy {
    public: GoodBoy();
           ~GoodBoy();
    private:
        asdf_t* forMyEyesOnly; // Only a pointer - definition not needed!
    }
    

    But it cannot have this:

    class BadGirl {
    public BadGirl();
          ~BadGirl();
    private:
        asdf_t notForAnyOneToSee; // Won't compile - would need definition.
    }
    

    Why is this done?

    Normally, it's because the creators of the library you are using don't want you to know the details of that structure! However, they have to provide such a 'minimial' definition, so that you can use classes, et cetera, that - by necessity - use or reference that structure: So, for example, in the implementation of the GoodBoy class (i.e. private source files, in which the full definition is given for asdf_t), one could have the constructor and destructor doing something like, say:

    GoodBoy::GoodBoy() {
        forMyEyesOnly = new asdf_t; // Note: Neither the 'new' operation, nor...
    }
    GoodBoy::~GoodBoy() {
        delete forMyEyesOnly; // ...the 'delete' can compile without FULL DEFINITION!
    }
    

    Clarification

    Normally, such an opaque structure is declared simply by: struct asdf_t;! However, both typedef struct asdf_t asdf_t; and typedef struct asdf_t; are also valid syntax (if a little weird).

    Further Reading

    There's a good (if a little old) Stack Overflow discussion on opaque structures, and how to declare them, here.