As your final lesson on classes, we'd like to diverge from the syntax to teach about a bit of what is considered good programming style when you use classes. After all, what good is a mouth-watering enchilada if it isn't served with a bit of flair? First of all, there is the golden rule of classes: "If it doesn't HAVE to be public, then make it private". Following this will prevent a lot of mistakes where you try to go around a data member's Get and Set methods. Doing so may not have any effect at first, but if you later decide to change how the data is represented in the class, then it is much simpler if you only have to change the code of the Get and Set methods than go through your code and change every mention of that data member. And now that we've seen how to define class methods outside of the class definition, we can introduce another key stylistic point, the separation of .h and .cpp files. The basic idea is simple: put all of your class definitions in one header file, and then put the method definitions in a another file which includes the header file. This reduces clutter and separates the implementation of the class from the definition of its interface. Using our last class as an example, here is how you would split a class up into two files. nacho.h: class Nacho { public: void Prompt(); private: int num; }; nacho.cpp: #include <nacho.h> void Nacho::Prompt() { cout << "Would you like that nacho with or without cheese?"; cin >> num; if (num > 10) cout << "Wow, that's a lot of nachos, you must be hungry!"; } / The rest of your code, including main, goes here |