Re: Object-oriented programming in standard ANSI C



On Sat, 18 Nov 2006 20:32:41 GMT, Keith Thompson wrote:
"E. Robert Tisdale" writes:
[...]
You probably meant "data hiding".
The C computer programming language allows you to encapsulate data
[in a struct] but it doesn't support data hiding at all.

There have been many discussions whether encapsulation and information
hiding are the same or whether one is a means for the other. Let's
assume we mean that data should not be accessible from the 'outside'.

It doesn't? At all?

Using an opaque data types
(publishing a struct declaration without publishing it's definition)
precludes some compile time optimizations.

Ah, so it *does* support data hiding.

I've always wondered why C programmers often unnecessarily give up
encapsulation. You can frequently see code like the following:

struct my_struct {
// some data
};
typedef struct my_struct my_struct;

my_struct* init (int i);
int do_something (my_struct* p, int n, float f);
// more functions
void cleanup (my_struct* p);

In the above example the my_struct definition in the header file is
unnecessary, a forward declaration (struct my_struct;) is sufficient.
The user not only gets access to 'private' data but also the my_struct
data become part of the published interface. This means that future
releases of the code cannot alter that data any more (not even
rearrange them) without potentially breaking existing code. Sometimes
the (generous) use of macros prevents encapsulation but in many cases
lack of encapsulation seems to be just an oversight of the programmer.

Best regards,
Roland Pibinger
.



Relevant Pages

  • Re: OOP/OOD Philosophy
    ... This style of encapsulation is far better than ... >>> struct Point { ... It adds dynamic polymorphism to the mix. ...
    (comp.object)
  • Re: OOP/OOD Philosophy
    ... >>>I'm with Isaac, where is the encapsulation? ... >> struct Point { ... My point was that languages like C had stateful encapsulated "objects" ... It adds dynamic polymorphism to the mix. ...
    (comp.object)
  • Re: void pointers
    ... >> think) where a struct held only data and a class was much as it is now, ... I was referring to encapsulation. ... Sounds like you're referring to "data hiding", ... It can be changed at any time with proper access specifiers. ...
    (comp.lang.cpp)
  • Re: why still use C?
    ... > the struct type 'data'. ... This is no encapsulation. ... > Nothing at all to do with 'functional programming'. ...
    (comp.lang.c)
  • Re: reading from a serial port
    ... >> array of structs, it uses a pointer to one element in an array ... >far enough to know that FILE is possibly a typedef to some struct. ... Ritchie, "The C Programming Language", 2nd Edition. ... the stdio library allocates a data buffer (BUFSIZ in stdio.h is ...
    (comp.unix.programmer)