A typedef of the following form:
typedef struct S *SPtr;
does not need prior knowledge of what S
is in the same translation unit. It assumes a forward declaration of some structure S
and aliases SPtr
as a pointer type to said-same. However, this:
typedef S *SPtr; // error unless S is declared earlier
requires the declaration of the type S
(which may be a structure) is already known prior to the declaration of the pointer alias type.
While this may seem trivial, it is a cornerstone of common implementations of the pimpl idiom. Note the typedef
isn't really involved here, the announcement of struct MyClassImpl*
as a pointer type to an unknown "thing" to-be-determined later (but prior to actual dereference) is what is important:
MyClass.h
#ifndef MY_CLASS
#define MY_CLASS
class MyClass
{
... members ...
private:
struct MyClassImpl * m_pimpl; // note no MyClassImpl yet known
};
#endif
MyClass.cpp
#include "MyClass.h"
// implementation formal declaration and implementation.
struct MyClassImpl
{
... members...
};
// MyClass implementation using the now-known MyClassImpl
Had that pointer been declared as:
MyClassImpl * m_pimpl;
the type MyClassImpl
would require prior declaration or a compile-time error would ensue.
I hope that helps identify a key difference between the two methods of declaration. (and yes, I know, I should have used a smart pointer =P)
Best of luck.