D   A   T   A   W   O   K

Creation: March 31 2016
Modified: February 05 2022

Data Encapsulation in C

This article is part of a series that faces the implementation of four of the most fundamental concepts of object-oriented programming using the standard C programming language:

I assume that you are already familiar with object-oriented programming. Thus, for every subject, a very short theoretical introduction is given.

Encapsulation is the principle of segregation of the design decisions of a piece of code. The technique is particularly usefull in the context of library implementation when we want to keep away the user from the details or if the internals are subject to change.

Encapsulation is often achieved through information hiding that can be implemented by keeping the definitions of the structures in the source file rather that in the associated header.

Because the user have no more idea about how the used data type is internally composed it is forced to use the type only via its interface.

A pointer to the structure defined in a source file is often called an opaque pointer.

This safety comes at a price, objects without definitions are no more instantiable as global variables and/or in the stack. The user is allowed to create such objects only dynamically through creation functions that will store the data into the heap. This is not always a desiderable feature.

Furthermore, because the data is allocated dynamically in the heap, the user must remember to delete the created data when it is no more needed.

object_type *obj = object_create(args);    /* the only way to create an object */
/* use it ... */
object_delete(obj); /* remember to delete the object */


Starting from the abstraction example we just need to move the stack structure definition from the header file to the source file. In the header file just add the opaque structure forward declaration to inform the compiler about the existance of such type.

struct stack;
typedef struct stack stack_t;

Example sources download

Proudly self-hosted on a cheap Raspberry Pi