This is a valid, working class declaration for a Player object. All we did
is declared the member data (variables for the player object) and the member functions
(functions which our object can do use), and then enclosed them inside the class
declaration block. A class declaration block do consists of a keyword class, followed by
name of an object, in this case the class name is Player, pair of braces, and the
A Member Data
A class player can have attributes like health,strength, ability etc. These attributes of
a class are called memeber data. These can be either private, public or protected
Private members are those which can only be accessed by the member funtions where as the
Public members can be accessed by any functions in the program.
A Member Function
Player object can have the behavours like
Move, AttackMonster and GetTreasure. Till now we mentioned what a player can do and
not how the Player can execute these functions. We need to write the function body for
each of the function, so that a Player instance will come to know how to attack the
monster, Here is a syntax for writing the function definition for the member function:
//function body goes here
It is almost similar to writing the function definition for the plain-old,
stand-alone functions. Only difference here is that we do precede the name of a function,
with the object name here move(), with the Player object, and a scope resolution
operator :: which tells a compiler that this function is the part of the Player class.
Instantiating an Object
Creating an object is similar to creating a simple variable. Let us say assume that we
want four players in the game, each of them trying to find their way to end of the maze
faster than the other player. This can be done by creating four instances of Player
object as shown below.
Though all these objects are Players, they are independent from one another. They are
created by a same template, but they do have some different attributes. Take for example,
"blueHat" may be a slow and strong player, while a "greenHat" may be quick but weak, and
an "yellowHat" may be well balanced individual, etc. Things which will make these objects
similar is they all should have the values for a strength, health, and the ability.
but they all are different as each of them can each have their own values for these
attributes. So an object is intantiated or created by prefixing a class name to the object name as
Using the Object's Mmember Functions
Once the object is been created it is time to know how to use the object.
Using the object means using up an member data and member funtions of an object.
Suppose we have an object greenHat. The behaviour (method) attackMonster can be accessed
as shown below. The memeber funtion is accessed using the dot operator.