Software & Finance





C++ - Encapsulation





When we have a class CStudent defined in the given example below, the programmers can not access the member variables directly. They need to go through the Get and Set functions. This explains the concepts of encapsulation. It also explains the concept of data hiding. Using private keyword, the data and methods of the functions can be hidden or can be accessible only by the class members. We can extend the access level to derived classes by using protected keyword.

Sample Code


class CStudent

{

private:

char name[128];

int age;

char addr1[128];

char addr2[128];

char city[32];

char zipcode[10];

 

public:

CStudent() {}

~CStudent() {}

 

const char* GetName() const { return name; }

const char* GetAddr1() const { return addr1; }

const char* GetAddr2() const { return addr2; }

const char* GetCity() const { return city; }

const char* GetZipCode() const { return zipcode; }

int GetAge() const { return age; }

 

void SetName(const char* p) { strcpy(name, p); }

void SetAddr1(const char* p) { strcpy(addr1, p); }

void SetAddr2(const char* p) { strcpy(addr2, p); }

void SetCity(const char* p) { strcpy(city, p); }

void SetZipCode(const char* p) { strcpy(zipcode, p); }

void GetAge(int v) { age = v; }

};