(★★★) The class Keyword

Posted: March 9, 2011 in C++

Syntax for the class keyword is as follows:

class class_name
         //access control keywords here
         //class variables and methods declared here

You use the class keyword to declare new types. A class is a collection of class member data, which are variable 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 variable. 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 acess 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 acess control keyword. Class declarations end with a closing brace and a semicolon.

Example 1:

class Cat
         unsigned int Age;
         unsigned int Weight;
         void Meow();

Cat Frisky;
Frisky.Age = 8;
Frisky.Weight = 18;

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 = OlFaithful.GetYear();                      //set bought to 84



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s