FAQ 2.16 What are the basics of creating class header files?

graphics/new_icon.gif

The first step is to remember #ifndef.

When creating a class header file, the first thing to remember is to wrap the header in #ifndef, #define, and #endif lines, just as with C header files. The following shows the skeleton of the header file that defines C++ class Car.

 #ifndef CAR_HPP #define CAR_HPP class Car { public:                                                      <-- 1 protected:                                                      <-- 2 }; #endif 

(1) The member functions for Car objects are declared here

(2) The data members for Car objects are declared here

This code might be stored in the header file "Car.hpp".

The public: and protected: parts of the class are different: normal user code (e.g., main()) can access only public: features. If normal user code tries to access anything in the protected: part, the user code would get a compile-time error (not a warning: a true error, something that would have to be fixed before getting the code to compile). This is called encapsulation, and is described further in FAQ 5.16.

Although public: and protected: are quite different with respect to encapsulation, they are very similar otherwise. The public: part can also contain data, and the protected: part can also contain member functions. In fact, they are completely symmetrical: data and member functions can be declared in either section. It's generally considered unwise (and unnecessary) to create public: data, but protected: member functions are fairly common and quite useful. For example, protected: member functions can be helper functions that are used mainly by the public: member functions (analogous to static functions within a module in C).



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