|
| |
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:
 | Prefer using protected members for non-public members and member functions
versus private.
 | 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.
|
|
 | Always provide a constructor, destructor, copy constructor, and assignment
operator as
these are present in EVERY class.
 | 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. |
 | Always 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.
|
|
 | Always 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.
 | Failure 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. |
|
 | Never "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. |
|