Sams Teach Yourself C++ in 21 Days

(singke) #1
49: void Cat::Meow()
50: {
51: std::cout << “Meow.\n”;
52: }
53:
54: // demonstrate various violations of the
55: // interface, and resulting compiler errors
56: int main()
57: {
58: Cat Frisky; // doesn’t match declaration
59: Frisky.Meow();
60: Frisky.Bark(); // No, silly, cat’s can’t bark.
61: Frisky.itsAge = 7; // itsAge is private
62: return 0;
63: }

As it is written, this program doesn’t compile. Therefore, there is no output.

This program was fun to write because so many errors are in it.
Line 10 declares GetAge()to be a constaccessor function—as it should be. In the body
of GetAge(), however, on line 32, the member variable itsAgeis incremented. Because
this method is declared to be const, it must not change the value of itsAge. Therefore, it
is flagged as an error when the program is compiled.
On line 12,Meow()is not declared const. Although this is not an error, it is poor pro-
gramming practice. A better design takes into account that this method doesn’t change
the member variables of Cat. Therefore,Meow()should be const.
Line 58 shows the creation of a Catobject,Frisky. Catnow has a constructor, which
takes an integer as a parameter. This means that you must pass in a parameter. Because
no parameter exists on line 58, it is flagged as an error.

160 Day 6


LISTING6.5 continued

ANALYSIS

If you provide anyconstructor, the compiler will not provide one at all. Thus,
if you create a constructor that takes a parameter, you then have no default
constructor unless you write your own.

NOTE

Line 60 shows a call to a class method,Bark(). Bark()was never declared. Therefore, it
is illegal.
Free download pdf