Opaque Pointers Concept
Part of the Object Oriented Programming section of Coddy's C journey — lesson 17 of 61.
So far, when we define a struct in a header file, anyone who includes that header can see and directly access all its members. This breaks encapsulation—the principle of hiding internal details from outside code.
C provides a powerful technique called opaque pointers to solve this. The idea is simple: declare that a struct exists in the header, but don't reveal what's inside it. This is done using an incomplete type:
// wallet.h
typedef struct Wallet Wallet; // Declaration only - no body!
Wallet *create_wallet(int initial_balance);
void free_wallet(Wallet *w);
Notice there are no curly braces—we never define what Wallet contains. The compiler knows the type exists, but not its size or members. This means code that includes this header can only work with pointers to Wallet, never the struct itself directly.
Why does this matter? Because the actual struct definition lives hidden in the .c file, any code using your header cannot write w->balance or sizeof(Wallet). They must use the functions you provide. You control all access to the data, and you can change the internal structure later without breaking any code that depends on your header.
In the next lesson, you'll practice defining the actual struct body inside the source file, completing the opaque pointer pattern.
Cheat sheet
An opaque pointer uses an incomplete type to hide struct implementation details, enforcing encapsulation.
Declare the struct in the header without defining its body:
// wallet.h
typedef struct Wallet Wallet; // Declaration only - no curly braces
Wallet *create_wallet(int initial_balance);
void free_wallet(Wallet *w);
The compiler knows the type exists but not its size or members. Users can only work with pointers to the struct and must use provided functions to interact with it.
The actual struct definition is placed in the .c file, preventing direct member access like w->balance or use of sizeof(Wallet).
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Modular Programming Basics
Header FilesInclude GuardsSource FilesStatic FunctionsRecap: Modular Calculator4Encapsulation
Opaque Pointers ConceptDefining Opaque StructsGetters and SettersValidation in SettersRecap: Secret Box2Objects and Methods
Structs as ObjectsThe 'Self' PointerConst CorrectnessPointer vs ValueHelper MethodsRecap: Point Manager5Project: Simple Bank Account
Project SetupImplementation of Account3Object Lifecycle
Constructor PatternDestructor PatternStack InitializationDeep CopyRecap: String Wrapper6Inheritance via Composition
Struct EmbeddingThe First Member RuleAccessing Parent MembersUpcastingRecap: Shape Hierarchy