Sigma Tech Corporation

Home Contents Search Contact Feedback Req Info

  Class Definition


Class Definition Freeware Books Links Submit Tip Submitted Tips

Up

 

When designing a class, following a few rules will make the class more robust, minimize improper usage, and allow for future classes to easily derive from your base class.  Following these easy guidelines will assist you in having the "perfect" class without shifting focus from what the class needs to do:

bulletPrefer using protected members for non-public members and member functions versus private.
bullet Using protected still prevents users of the class from accessing the variables/functions, but allows future classes that may wish to derive from your class to have full access.  Using private member variables and functions precludes future derived classes from publicly inheriting from your class.
 
bulletAlways provide a constructor, destructor, copy constructor, and assignment operator as these are present in EVERY class.
bullet If you don't define these functions,  the compiler will, and if there are any resources allocated in your class, they will be leaked.  If you wish for users or derived classes not to be able to use these member functions consider making them protected or private.
bulletAlways providing these functions (even if protected or private) is better style than allowing compiler generated functions, and will allow derived classes to properly inherit these functions as necessary.
 
bulletAlways provide a virtual destructor in any class that will be used as a base class, and its corollary NEVER derive a new class from a base class WITHOUT a virtual destructor.
bulletFailure to heed this rule, will generally cause the base class destructor not to be automatically called during the destruction process, so any resources allocated in the construction of the base class will be leaked.  One could however call the base class constructor implicitly, but as a general rule of thumb, if a virtual destructor is not provided in a class it should be considered a concrete class, and not be derived from.
bulletNever "override" a member function in a base class that is not virtual.  Doing this causes "slicing" where the base class function will be called sometimes, and the inherited class function other times, depending on the pointer to the object.

 

 

Home ] Up ]

Copyright © 1996-2005 Sigma Tech Corporation
Last modified: December 18, 2005