Get and Set ("private") in C disadvantages? -
Get and Set ("private") in C disadvantages? -
i wanted create struct in c info couldn't accessed directly, through gets , sets in object oriented. solution like:
point.h
#ifndef point_h #define point_h typedef struct point point; point *createpoint(int x, int y); int point_getx(point *point); void point_setx(point *point, int x); int point_gety(point *point); void point_sety(point *point, int y); void deletepoint(point **p); #endif /* point_h */
point.c
#include "point.h" struct point{ int x, y; }; point *createpoint(int x, int y){ point *p = malloc(sizeof(point)); if (p == null) homecoming null; p->x = x; p->y = y; homecoming p; } int point_getx(point *point){ homecoming point->x; } void point_setx(point *point, int x){ point->x = x; } int point_gety(point *point){ homecoming point->y; } void point_sety(point *point, int y){ point->y = y; } void deletepoint(point **p){ if (*p != null){ free(*p); *p = null; } }
main.c
#include <stdio.h> #include <stdlib.h> #include "point.h" int main(){ point *p = createpoint(2, 6); if (p == null) homecoming exit_failure; /* p->x = 4; "error: dereferencing pointer p->y = 9; incomplete type" */ point_setx(p, 4); point_sety(p, 9); printf("point(%d,%d)", point_getx(p), point_gety(p)); deletepoint(&p); homecoming exit_success; }
of course of study i'd never simple point, that's idea. want know go wrong doing this, whether should doing or not, , if it's ok this, if it's not smart approach (and should go c++ xd). reason of i'm doing little project may alter info structures , algorithms later on, if this, need alter point.c in case, , not every single place i'd do
point->x = new_x
for example.
basically, trying c++ do? or it's ok in c? or not, there's disadvantage? or not c meant be? haha
my solution [this]
this classic solution in c info hiding. missing thing destroypoint
, function deallocate point construction allocate malloc
.
i want know go wrong doing this, whether should doing or not, , if it's ok this.
it safe approach, long ok disadvantage, described below.
[is there] disadvantage?
yes, there is: approach limited dynamic allocation of info structures internals of hide. cannot this:
point p; // fails, because `point` forwards declaration. int x = point_getx(&p);
similarly, arrays of point
s off-limit; embedding of point
s in other struct
s not possible well.
am trying c++ does?
not really. approach similar objective-c, because c++ not have limitation of allocating objects in dynamic store, while objective-c does. limitation not seem create much problems objective-c programmers, though.
c private
Comments
Post a Comment