What is a Class?
A class can be described as a group of objects. The class consists of member variables, which are variables in the class, and you will also have member functions, which are functions in the class. Here is a good way to think of a class and objects. Lets think of the real world for a second, I’m going to focus on a light switch. What can the light switch do? Well it can turn the light on and off. If you make a diagram out of this, it could look like this:
 | |  | | |
{FIG}
void turnOn();
void turnOff();
|
|  |
|
As you can see the class name is LightSwitch and the class performs two functions, turnOn and turnOff. If you wanted to declare this class you would do so as follows:
 | |  | | |
//tq.h
class LightSwitch
{
public:
void turnOn() { cout <<"Light Switch on!nn";}
void turnOff() { cout <<"Light Switch off!n";}
}; |
|  |
|
You may be a little confused by some keywords used in this code but I’ll explain them now. Every time you go to declare a class you start off with the keyword class followed by the name of the class. Here is an example of the syntax:
 | |  | | |
class NameOfClass
{
public:
//code, member functions
private:
//member variables
}; |
|  |
|
The declaration begins with the keyword class followed by the name of the class. There must be 2 braces, one at the begining and one at the end followed by a semicolon, for example class Cat { }; After the first brace you see the keyword public. Public members can be accessed outside the class, while private members are only accessible from within the class. It’s always a good idea to make the member variables, such as int itsAge; private so that the variables can only be accessed from within the class; this is called “information hiding.” It will make the code easier to understand and to debug at a later stage. Member functions are just functions inside the class. In the above example of the light switch, the member functions of that class would have been void turnOn() and void turnoff(). Member variables are just variables inside the class, such as int itsAge, itsWeight.
Please Rate this Code:
Comments for: What is a Class?
Annonymouse User says:
It was easy to understand good explanation. |
 |
 |
|
 |
|
 |