Encapsulation/Incorporation

Hi All,

I am having a little trouble wrapping my head around something my professor said, I am hoping someone can help my brain click. He said that encapsulation, along with the incorpration of range checking logic, will help create smarter objects. I understand encapsulation, incorporation and range checking, just drawing a blank when thinking about everything together. Easy on the greenhorn :). Thanks!
I think that incorporating of range checking logic means that methods of a class check acceptable range of values for an objefct. For example the index of an array can be checked against its size.
Last edited on
OK, I get that. Where does encapsulation come in? The methods of a class are public. The values that are encapsulated are usually static or constant. Or am I missing something.
Take this example of a class which stores the birthday for a person:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Birthday 
{
public: 
     voidPrintBirthdate() const; //prints the whole birthday to screen
     /*The following three functions retrieve their specific data from the user
        and check to see if it is acceptable (the year is not greater than the 
        current year, the month is not less than one or greater than 12, 
        ect.). There are many ways to handle the check, one would be to
        return false if the information given is incorrect.*/
     bool getBirthYear();          
     bool getBirthMonth();       
     bool getBirthDay();     
private:
     /*The set functions are called by their corresponding get functions AFTER
         the input data has been verified*/
     void setBirthYear();
     void setBirthMonth();
     void setBirthDay();

     int year;
     int month;
     int day;
};


The three member variables, year month and day are all encapsulated and protected from the user. The user cannot directly access or modify them. Only from accessing the get function and having the data verified can the user then have any of these variables changed (note the set functions are also private and cannot be directly called by the user.)
Last edited on
OK, looking at the code has flipped a switch. I believe I now understand better. Thanks to both of you!!!
Ok, next question is how is the best way to implement the get/set functions.

class Birthday
{
public:
voidPrintBirthdate() const;
bool getBirthYear()
{
return year;
}
bool getBirthMonth()
{
return month;
}
bool getBirthDay()
{
return day;
}
private:
void setBirthYear();
void setBirthMonth();
void setBirthDay();

int year;
int month;
int day;
};

Or would it be something like
bool getBirthYear()
{
if (year < 1900) return 0;

return 1;
}
Last edited on
Topic archived. No new replies allowed.