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
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). |