Classes
At the heart of Object Oriented Programming is the concept of the class. A class is just a collection of attributes and behaviors or methods (a fancy OOP word for function) that define an object. We can use classes to model almost any object we want. A chair is an object. It has four legs, it is three feet high, it weighs 20 pounds, and it is made of wood. These are all attributes of a chair. A chair can spin, tile or be smashed to bits. These are the behaviors of a chair. Likewise, a dog is an object. A dog has a name, age, and weight. These are a dog's attributes. A dog also has behaviors. A dog can eat, sleep and bark. Almost anything can be modeled as an object.
When we model an object in C++ we first create a class definition. This is usually stored in a header file. Let's create a Dog class:
|
#ifndef DOG_H_ #define DOG_H_ class Dog { public: //constructor //accessors //modifiers //behaviors private: //attributes }; #endif |
This is a class skeleton. We will be adding to it until we have a complete class. Let's look at each line:
|
#ifndef DOG_H_ #define DOG_H_ |
If you have never seen that before, those are preprocessor directives. They simply tell the compiler, "if DOG_H_ is not defined, then define it and do all the stuff until you see #endif. If you have seen DOG_H_, then just ignore all the stuff until after #endif". This a way to prevent a header file from being #included into the same .cpp file more than once which can be dangerous. Use the #ifndef, #define, #endif combo in ALL of your header files, just change DOG_H_ to the name of the header file. The next line is actually the start of the Dog class:
|
class Dog { |
We have a new keyword called class. This keyword creates a new data type. The data type is called Dog. Now for the inside of a class:
|
public: //constructor //accessors //modifiers //behaviors private: //attributes }; #endif |
We will look at each part of the class, but first let's focus on some more new keywords: public and private. Public and private refer to the "visibility" of the classes members. When we talk about visibility we are talking about the world outside of the class. Members contained after the word public are visible to everyone, that means they can be accessed and modified outside of the class. Members contained after the word private are only visible within the class itself, the outside world cannot see or modify them. You don't have to completely understand that yet, just keep it in mind.