Class Functions
Here is an example of using both public and private.
 | |  | | |
//employee.h
class Employee
{
public:
void setAge(int age){ itsAge = age;}
int getAge() { return itsAge;}
void setYears(int years) { itsYears = years;}
int getYears() { return itsYears;}
private:
int itsAge;
int itsYears;
}; |
|  |
|
In this class we have four member functions and two member variables. The way I typed the functions all in one line was to save room. void setAge(int age){ itsAge = age;} could be written as:
 | |  | | |
void Employee::setAge(intAge)
{
itsAge = age;
} |
|  |
|
These functions are very basic and simple. I’ll explain the first two member functions because the other two fulfill the same role but just access and set different member variables. The first function,
 | |  | | |
void setAge(int age){ itsAge = age;} |
|  |
|
takes one parameter int age, and in the body of the function it takes the enter value and sets it as the member variable itsAge; The second member function,
 | |  | | |
int getAge() { return itsAge;} |
|  |
|
takes no parameters because all its going to do is return itsAge; its as simple as that!Please Rate this Code:
Comments for: Class Functions
Annonymouse User says:
I would have made itsAge and itsYears puplic. That way, you only need two funtions, but it doesnt really illustrate what this is all about, so. |
 |
 |
|
 |
|
 |