Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 161

6


Line 61 shows itsAgebeing assigned the value 7. Because itsAgeis a private data
member, it is flagged as an error when the program is compiled.

Why Use the Compiler to Catch Errors?
Although it would be wonderful to write 100 percent bug-free code, few programmers
have been able to do so. However, many programmers have developed a system to help
minimize bugs by catching and fixing them early in the process.
Although compiler errors are infuriating and are the bane of a programmer’s existence,
they are far better than the alternative. A weakly typed language enables you to violate
your contracts without a peep from the compiler, but your program crashes at runtime—
when, for example, your boss is watching. Worse yet, testing is of comparatively little
help in catching errors, because there are too many paths through real programs to have
any hope of testing them all.
Compile-time errors—that is, errors found while you are compiling—are far better than
runtime errors—that is, errors found while you are executing the program. This is
because compile-time errors can be found much more reliably. It is possible to run a pro-
gram many times without going down every possible code path. Thus, a runtime error
can hide for quite a while. Compile-time errors are found every time you compile. Thus,
they are easier to identify and fix. It is the goal of quality programming to ensure that
the code has no runtime bugs. One tried-and-true technique to accomplish this is to use
the compiler to catch your mistakes early in the development process.

Where to Put Class Declarations and Method Definitions..................................


Each function that you declare for your class must have a definition. The definition is
also called the function implementation. Like other functions, the definition of a class
method has a function header and a function body.
The definition must be in a file that the compiler can find. Most C++ compilers want that
file to end with .cor .cpp. This book uses .cpp, but check your compiler to see what it
prefers.

Many compilers assume that files ending with .care C programs, and that
C++ program files end with .cpp. You can use any extension, but .cppmini-
mizes confusion.

NOTE

Free download pdf