FAQ 2.18 What are the basics of defining member functions?

graphics/new_icon.gif

Member functions are normally defined in the source file associated with the class (but see FAQ 13.01. For example, if the header file is called "Car.hpp", the source file might be called "Car.cpp". Here is an example of the header file Car.hpp:

 #ifndef CAR_HPP #define CAR_HPP class Car { public:   virtual void startEngine();                        <-- 1   // ... protected:   bool isRunning_;   bool radioOnAM_;   int  radioFreq_; }; #endif 

(1) Declare a member function

Here is an example of the source file Car.cpp:

 #include "Car.hpp"                                   <-- 1 void Car::startEngine()                              <-- 2 {   isRunning_ = true;   // ... } 

(1) Get the Car class

(2) Define a member function.

The line void Car::startEngine() tells the compiler that this is the definition of the startEngine() member function from the Car class. If this just said void startEngine() { ... } the compiler would think that a non-member function was being defined, as opposed to the startEngine() member function of the Car class.

The line isRunning_ = true; sets the protected: data member isRunning_ to true. If Car a; a.startEngine(); has been executed, this line would set a.isRunning_ to true (even though a.isRunning_ is protected: it does exist and can be accessed by member functions of the Car class).



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