FAQ 2.17 What are the basics of defining a class?

graphics/new_icon.gif

By convention, the public: part goes first. The following example shows the header file that defines C++ class Car.

 #ifndef CAR_HPP #define CAR_HPP #include <string> class Car { public:   virtual void startEngine();                        <-- 1   virtual bool isRunning() const;                    <-- 2   virtual void tuneRadioTo(const string& band, int freq);   <-- 3 protected:   bool isRunning_;                                   <-- 4   bool radioOnAM_;   int  radioFreq_; }; #endif 

(1) Line 1

(2) Line 2

(3) Line 3

(4) Line 4

Line 1 declares a member function of class Car. This member function doesn't take any parameters. Note that C programmers use (void) to declare a function that takes no parameters, but this is not necessary in C++. Be warned that some C++ developers consider the (void) syntax in C++ code to be an indicator that the author of the code is still a warmed-over C programmer that the author hasn't yet made the paradigm shift. This is an unfair judgment, but it might be wise to use () rather than (void) in C++ code.

Line 2 declares another member function, this time returning a bool (the bool data type has two values: true and false). The member function's name is designed to make sense in an if statement, e.g., if (myCar.isRunning())...The const on the right side means that the member function is an inspector it promises not to change the object. This lets users know that the Car object won't suddenly change inside a statement such as if (myCar.isRunning()). It is a good idea to mark every member function that is logically an inspector with a const; otherwise the compiler will give error messages when someone calls one of these member functions via a reference-to-const or a pointer-to-const (see FAQ 2.09, 2.11).

Line 3 declares another member function, this time taking two parameters. Member functions that don't have a const on the right side are known as mutator member functions, since they can change the object. For example the statement myCar.tuneRadioTo("AM",770) probably makes changes to the Car object called myCar.

Line 4 declares a data member. By convention, data member names end with an underscore. This particular data member is presumably used by the isRunning() member function.

UML uses the following notation to show a class Car that contains member functions startEngine(), isRunning(), and tuneRadioTo(), and that contains data members called isRunning_, radioOnAM_, and radioFreq_:

graphics/02fig03.gif



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net