Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 159

6


LISTING6.5 A Demonstration of Violations of the Interface


1: // Demonstrates compiler errors
2: // This program does not compile!
3: #include <iostream> // for cout
4:
5: class Cat
6: {
7: public:
8: Cat(int initialAge);
9: ~Cat();
10: int GetAge() const; // const accessor function
11: void SetAge (int age);
12: void Meow();
13: private:
14: int itsAge;
15: };
16:
17: // constructor of Cat,
18: Cat::Cat(int initialAge)
19: {
20: itsAge = initialAge;
21: std::cout << “Cat Constructor\n”;
22: }
23:
24: Cat::~Cat() // destructor, takes no action
25: {
26: std::cout << “Cat Destructor\n”;
27: }
28: // GetAge, const function
29: // but we violate const!
30: int Cat::GetAge() const
31: {
32: return (itsAge++); // violates const!
33: }
34:
35: // definition of SetAge, public
36: // accessor function
37:
38: void Cat::SetAge(int age)
39: {
40: // set member variable its age to
41: // value passed in by parameter age
42: itsAge = age;
43: }
44:
45: // definition of Meow method
46: // returns: void
47: // parameters: None
48: // action: Prints “meow” to screen
Free download pdf