Understanding Object-Oriented Programming 143
6
you use the dot operator (.) to access the members of that object. Therefore, to assign 50
to Frisky’s Weightmember variable, you would write
Frisky.itsWeight = 50;
In the same way, to call the Meow()function, you would write
Frisky.Meow();
When you use a class method, you call the method. In this example, you are calling
Meow()on Frisky.
Assigning to Objects, Not to Classes ............................................................
In C++, you don’t assign values to types; you assign values to variables. For example,
you would never write
int = 5; // wrong
The compiler would flag this as an error because you can’t assign 5 to an integer. Rather,
you must define an integer variable and assign 5 to that variable. For example,
int x; // define x to be an int
x = 5; // set x’s value to 5
This is a shorthand way of saying, “Assign 5 to the variable x, which is of type int.” In
the same way, you wouldn’t write
Cat.itsAge=5; // wrong
The compiler would flag this as an error because you can’t assign 5 to the age part of a
class called Cat. Rather, you must define a specific Catobject and assign 5 to that object.
For example,
Cat Frisky; // just like int x;
Frisky.itsAge = 5; // just like x = 5;
If You Don’t Declare It, Your Class Won’t Have It ........................................
Try this experiment: Walk up to a three-year-old and show her a cat. Then say, “This is
Frisky. Frisky knows a trick. Frisky, bark.” The child will giggle and say, “No, silly, cats
can’t bark.”
If you wrote
Cat Frisky; // make a Cat named Frisky
Frisky.Bark() // tell Frisky to bark
the compiler would say, “No, silly,Cats can’t bark.” (Your compiler’s wording will prob-
ably look more like “[531] Error: Member function Bark not found in class Cat”.) The