Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 163

6


You can also put the definition of a function into the declaration of the class, which auto-
matically makes that function inline. For example,
class Cat
{
public:
int GetWeight() { return itsWeight; } // inline
void SetWeight(int aWeight);
};
Note the syntax of the GetWeight()definition. The body of the inlinefunction begins
immediately after the declaration of the class method; no semicolon is used after the
parentheses. Like any function, the definition begins with an opening brace and ends
with a closing brace. As usual, whitespace doesn’t matter; you could have written the
declaration as
class Cat
{
public:
int GetWeight() const
{
return itsWeight;
} // inline
void SetWeight(int aWeight);
};
Listings 6.6 and 6.7 re-create the Catclass, but they put the declaration in Cat.hppand
the implementation of the functions in Cat.cpp. Listing 6.7 also changes the accessor
functions and the Meow()function to inline.

LISTING6.6 CatClass Declaration in Cat.hpp


1: #include <iostream>
2: class Cat
3: {
4: public:
5: Cat (int initialAge);
6: ~Cat();
7: int GetAge() const { return itsAge;} // inline!
8: void SetAge (int age) { itsAge = age;} // inline!
9: void Meow() const { std::cout << “Meow.\n”;} // inline!
10: private:
11: int itsAge;
12: };
Free download pdf