Re: DATA Hiding in C.
You can achieve data hiding in C by doing the following.
1. Create a .h file and tell anyone that includes the file that there exists a struct.
2. Put the struct with all of its datamembers in the .c file.
3. Anyone using the .h file will see that there is a struct available but have to use the access function to use it.
By doing this you have achieved data hiding since no one can directly access your struct or any of their members.
Simple example below.
create your .h file.
------------
/* person.h */
#ifndef SPERSON_H
#define SPERSON_H
struct Person; //This line says that there _exists_ a struct called Person and does not show how it looks like.
typedef struct Person *pPerson;
pPerson createPerson(char* first_name, char* last_name, int age);
void printPerson(pPerson);
void changeSureNamePerson(pPerson, char* new_first_name);
#endif
----------
Create your .c file.
---------
/* person.c */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "person.h"
struct sPerson
{
char surename[30];
char lastname[30];
int ager;
};
pPerson createPerson(char* surename,char* lastname, int age)
{
pPerson c = malloc(sizeof(struct Person));
assert (c != NULL);
strcpy(c->surename, surename);
strcpy(c->lastname, lastname);
c->age = age;
return c;
}
void printPerson(pPerson pers)
{
printf("Last name, Sure name, Age: %s %s %d\n", pers->lastname, pers->surename, pers->age);
}
void changeSureNamePerson(pPerson p, char* new_surename)
{
strcpy(p->surename, new_surename);
}
---------------
Create the main file.
-------------
#include <stdio.h>
#include <stdlib.h>
#include "person.h"
int main(void)
{
system("cls");
/* Put your own code here... */
pPerson *pers1 = createPerson("John", "Doe", 30);
printf("pers1 = ");
printPerson(pers1);
return 0;
}
------------
Hope this answered your question.
Regards,
Hybris