Re: C versus C++
On Jul 14, 5:18 pm, James Kanze <james.ka...@gmail.com> wrote:
And what's the first thing you do when you use C, and procedural
programming. You define a struct, a set of functions which
manipulate it, and cross your fingers that no client code
manipulates it other than through your struct.
Or you use C++, so you can declare the data members private.
<sigh> You don't cross your fingers. You provide
encapsulation through different methods. The following
is pure C, and all the data members are private:
#include <stdio.h>
#include <stdlib.h>
struct circle;
double get_area( const struct circle *);
struct circle *new_circle( double radius );
void free_circle( struct circle *);
int
main( int argc, char **argv)
{
double radius;
struct circle *c;
radius = argc > 1 ? strtod(argv[ 1 ], NULL) : 1;
c = new_circle( radius );
printf("radius: %f, Area: %f\n",
radius, get_area( c ));
free_circle( c );
return 0;
}
All you need to build an executable is the
object file, and you never even get to see the
layout of the struct circle. You don't
even know if I store the area when you create the
circle or if it's computed each time you invoke
get_area().
Encapsulation is indeed a wonderful thing, and
it can be accomplished in many ways. It often
seems that C++ has made it so that people never
even learn how to use a linker.