Encapsulation (computer programming): Difference between revisions

Content deleted Content added
Shnako (talk | contribs)
mNo edit summary
Line 61:
}
}
</source>
 
Encapsulation is also possible in older, non-object-oriented languages. In C, for example, a structure can be declared in the public API (i.e., the header file) for a set of functions that operate on an item of data containing data members that are not accessible to clients of the API:
<source lang="csharp">
// Header file "api.h"
 
struct Entity; // Opaque structure with hidden members
 
// API functions that operate on 'Entity' objects
extern struct Entity * open_entity(int id);
extern int process_entity(struct Entity *info);
extern void close_entity(struct Entity *info);
</source>
Clients call the API functions to allocate, operate on, and deallocate objects of an opaque type. The contents of this type are known and accessible only to the implementation of the API functions; clients cannot directly access its contents. The source code for these functions defines the actual contents of the structure:
<source lang="csharp">
// Implementation file "api.c"
 
#include "api.h"
 
// Complete definition of the 'Entity' object
struct Entity
{
int ent_id; // ID number
char ent_name[20]; // Name
... (etc.) ...
};
 
// API function implementations
struct Entity * open_entity(int id)
{ ... }
</source>