Sams Teach Yourself C++ in 21 Days

(singke) #1

Implementing Class Methods ..............................................................................


As you’ve seen, an accessor function provides a public interface to the private member
data of the class. Each accessor function, along with any other class methods that you
declare, must have an implementation. The implementation is called the function
definition.
A member function definition begins similarly to the definition of a regular function.
First, you state the return type that will come from the function, or void if nothing will
be returned. This is followed by the name of the class, two colons, the name of the func-
tion, and then the function’s parameters. Listing 6.3 shows the complete declaration of a
simple Catclass and the implementation of its accessor function and one general class
member function.

LISTING6.3 Implementing the Methods of a Simple Class
1: // Demonstrates declaration of a class and
2: // definition of class methods
3: #include <iostream> // for cout
4:
5: class Cat // begin declaration of the class
6: {
7: public: // begin public section
8: int GetAge(); // accessor function
9: void SetAge (int age); // accessor function
10: void Meow(); // general function
11: private: // begin private section
12: int itsAge; // member variable
13: };
14:
15: // GetAge, Public accessor function
16: // returns value of itsAge member
17: int Cat::GetAge()
18: {
19: return itsAge;
20: }
21:

150 Day 6


DOuse public accessor methods.
DOaccess private member variables from
within class member functions.

DON’Tdeclare member variables public
if you don’t need to.
DON’Ttry to use private member vari-
ables from outside the class.

DO DON’T

Free download pdf