Is there a terminology for "making a structure not directly accessible" in C?

I found some code in hostap . Below is a simplified one:

a.h

// it just declares 'there is a struct a'
struct a;

// it seems like an accessor to a private member b
int get_b(struct a);

      

a.c

// definition is seprated from a header file
struct a {
    int b;
};

int get_b(struct a) {
    return a.b;
}

      

An object file is created with these two files a.o

.

And if other source codes want to use struct a

, it cannot directly access the item b

, with the compiler complaining dereferencing incomplete type

. I can access the member b

with get_b()

.

For the first time, I am very frustrated with this pattern. But finally, I think this is a very well thought out pattern if someone wants to protect the integrity struct a

(for example, memebers values ​​must be set in certain criteria, or members depend on each other so that changing one member will affect the rest)

Is there a terminology for this type of template?

+3


source to share


2 answers


This is called an opaque type . You know there is a specific one struct

, but nothing else.

Since you don't know anything about the contents of the opaque structure, you cannot instantiate if there is one. However, you can create a pointer to it.

The example you give won't work because you will need to pass an instance struct a

to get_b

and you won't be able to create an instance struct a

. But if the function takes a pointer, you can do this:

int get_b(struct a *sa)
{
    return sa->b;
}

      



You will also need a constructor-like function to instantiate, since an external module cannot do this:

struct a *create(int b)
{
    struct a *tmp = malloc(sizeof(struct a));
    tmp->b = b;
    return tmp;
}

      

Then your title will contain:

struct a;

int get_b(struct a *);
struct a *create(int);

      

+7


source


hiding information , usually the Encapsulation component.



As noted by dbush and dasblinkenlight, this particular instance will be an opaque data type .

+1


source







All Articles