Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 149

6


// access control keywords here
// class variables and methods declared here
};

You use the classkeyword to declare new types. A class is a collection of class member
data, which are variables of various types, including other classes. The class also contains
class functions—or methods—which are functions used to manipulate the data in the
class and to perform other services for the class.
You define objects of the new type in much the same way in which you define any vari-
able. State the type (class) and then the variable name (the object). You access the class
members and functions by using the dot (.) operator.
You use access control keywords to declare sections of the class as public or private. The
default for access control is private. Each keyword changes the access control from that
point on to the end of the class or until the next access control keyword. Class declara-
tions end with a closing brace and a semicolon.
Example 1
class Cat
{
public:
unsigned int Age;
unsigned int Weight;
void Meow();
};
Cat Frisky;
Frisky.Age = 8;
Frisky.Weight = 18;
Frisky.Meow();


Example 2
class Car
{
public: // the next five are public
void Start();
void Accelerate();
void Brake();
void SetYear(int year);
int GetYear();
private: // the rest is private
int Year;
Char Model [255];
}; // end of class declaration
Car OldFaithful; // make an instance of car
int bought; // a local variable of type int
OldFaithful.SetYear(84) ; // assign 84 to the year
bought = OldFaithful.GetYear(); // set bought to 84
OldFaithful.Start(); // call the start method

Free download pdf