Search code examples
c++classvariablesscopeelaboration

Why use 'struct' keyword in class pointer declaration in C++


When and why should we use the 'struct' keyword when declaring a class pointer variable in C++?

I've seen this in embedded environments so I suspect that this is some kind of hold over from C. I've seen plenty of explanations on when to use the 'struct' keyword when declaring a struct object as it relates to namespaces in C (here), but I wasn't able to find anyone talking about why one might use it when declaring a class pointer variable.

Example, in CFoo.h:

class CFoo
{
public:
    int doStuff();
};

inline Foo::doStuff()
{
    return 7;
}

And later in a different class:

void CBar::interesting()
{
    struct CFoo *pCFoo;

    // Go on to do something interesting with pCFoo...
}

Solution

  • There's rarely a reason to do this: it's a fallover from C and in this case the programmer is simply being sentimental - perhaps it's there as a quest for readability. That said, it can be used in place of forward declarations.

    In some instances you might need to disambiguate, but that's not the case here. One example where disambiguation would be necessary is

    class foo{};
    
    int main()
    {
        int foo;
        class foo* pf1;
        struct foo* pf2;
    }
    

    Note that you can use class and struct interchangeably. You can use typename too which can be important when working with templates. The following is valid C++:

    class foo{};
    
    int main()
    {    
        class foo* pf1;
        struct foo* pf2;
        typename foo* pf3;
    }