Tips For Creating C++ Classes

When creating new C++ classes, especially as a beginning programmer, you can end up with a mess that is barely more than a bunch of function...

Monday, May 28, 2018

Tips For Creating C++ Classes

When creating new C++ classes, especially as a beginning programmer, you can end up with a mess that is barely more than a bunch of functions that you have to qualify with a class name. Before designing and writing a new class, keep the following ideals with OOP in mind.

  1.  This new class should be able to be used by any other program.  It should serve a useful purpose that someone besides yourself should find useful.
  2.  If your new class is going to be nothing but functions and hold very little or no data, consider a namespace instead.
  3. If your new class has more than two static functions, consider moving them into a namespace as well.
  4. If your application has more than two singleton objects, consolidate if possible.

Now when starting to code, start from the ground up.
  1. Start with the data.  The variables that this class will hold.  All of them *should* be private, unless there is a good reason not to for one or two.  Unless there is a reason, do not use unsigned variables.  -1 is awfully handy to indicate an error condition.
  2. Constructors... How will people most commonly use your class?  How can you make it as convenient as possible either inside your own application or someone else using it.
  3. Declare the functions you want public to do things with the data other than get/set it.
  4. Inside the header file write a set of generic get/set functions to access every member of data earlier declared private.  The reasons are varied and complex, but trust me in the long run its worth it.  Make them all quick little one line functions unless you need locking or something more complex.  This frees up your source file for the meat of the class's logic.
  5. And finally, the complex or working parts of the class, write in the source file.

No comments:

Post a Comment