How can I model private member variables in C ++ in C?

Is it possible to implement private member variables (like in C ++) in C and how can this be achieved? I was thinking of static global variables that limit the scope of a variable to just the file where it is defined, but how can I access it from other files? Is there a way to implement private member variables in C?

+4
source share
2 answers

To do this, you need to create an opaque type, two structures that start with the same fields, and then you can add private fields to one of them and never allow the user to access the private field.

Then provide access functions to modify / read private fields in the structure.

,

struct.c

#include <stdlib.h>

struct Private
{
    int public;
    int private;
};

struct Public
{
    int public;
};

struct Public *new_public(int private, int public)
{
    struct Private *instance;
    instance = malloc(sizeof(*instance));
    if (instance == NULL)
        return NULL;
    instance->private = private;
    instance->public  = public;

    return (struct Public *)instance;
}

int public_get_private(struct Public *public)
{
    if (public == NULL)
        return -1; /* or some invalid value */
    return ((struct Private *)public)->private;
}

void public_set_private(Public *public, int value)
{
    if (public == NULL)
        return;
    ((struct Private *)public)->private = value;
}

struct.h

#ifndef __STRUCT_H__
#define __STRUCT_H__

struct Public
{
    int public;
};

typedef struct Public Public;

Public *new_public(int private, int public);
int public_get_private(Public *instance);
void public_set_private(Public *instance, int value);
/* you can add more fields to the structures and more access functions */

#endif

main.c

#include "struct.h"

#include <stdlib.h>
#include <stdio.h>

int main()
{
    Public *instance;

    instance = new_public(1, 2);
    if (instance == NULL)
        return -1;
    printf("%d\n", instance->public);
    printf("%d\n", public_get_private(instance));

    free(instance);

    return 0;
}
  • new_public() .
  • private public_get_private(), -.
  • private Public.

, ,

Public *public = malloc(sizeof(*public));

, c, , , .

, , private , , .

+5

, ++. ( ) . , - .

, , .

/* header.h */
struct X {
    char private[SIZEOF_Y];
};

/* implementation.c */
struct Y {
    int private_a;
    float private_b;
};

union Z {
    struct X x;
    struct Y y;
};

, punning X Y. SIZEOF_Y , script, .

+1

All Articles