Sams Teach Yourself C++ in 21 Days

(singke) #1

140 Day 6



  • Coordinating the activities of groups of related functions on the structis harder
    because anything in the structcan be changed at any time by any piece of program
    logic. There is no way to protect structdata from interference.

  • The built-in operators don’t work on structs—it does not work to add two structs
    with a plus sign (+), even when that might be the most natural way to represent the
    solution to a problem (for instance, when each structrepresents a complex piece of
    text to be joined together).


Introducing Classes and Members ......................................................................


You make a new type in C++ by declaring a class. A class is just a collection of vari-
ables—often of different types—combined with a set of related functions.
One way to think about a car is as a collection of wheels, doors, seats, windows, and so
forth. Another way is to think about what a car can do: It can move, speed up, slow
down, stop, park, and so on. A class enables you to encapsulate, or bundle, these various
parts and various functions into one collection, which is called an object.
Encapsulating everything you know about a car into one class has a number of advan-
tages for a programmer. Everything is in one place, which makes it easy to refer to, copy,
and call on functions that manipulate the data. Likewise, clients of your class—that is,
the parts of the program that use your class—can use your object without worrying about
what is in it or how it works.
A class can consist of any combination of the variable types and also other class types.
The variables in the class are referred to as the member variables or data members. A Car
class might have member variables representing the seats, radio type, tires, and so forth.
Member variables, also known as data members, are the variables in your class. Member
variables are part of your class, just as the wheels and engine are part of your car.
A class can also contain functions called member functions or methods. Member func-
tions are as much a part of your class as the member variables. They determine what
your class can do.
The member functions in the class typically manipulate the member variables. For exam-
ple, methods of the Carclass might include Start()and Brake(). A Catclass might
have data members that represent age and weight; its methods might include Sleep(),
Meow(), and ChaseMice().
Free download pdf