Four easy and fun ways to get yourself into trouble with inheritance.
A frequent source of problems in OOP is called "breaking inheritance". This document briefly describes what inheritance is, how it applies to properties and methods, and how it can be maintained or broken. Problems appear especially when inheritance is broken in methods.
Inheritance with Properties
When creating an object or class based on another class, the child object (or class) initially inherits properties and methods from the parent class.
Example: Create a form class with a blue background. Use it as an ancestor (parent, grandparent, etc.) of all your forms. Now, all forms will have a blue background. Changing the background to red will change all forms based on it to red.
Now, if you change the background in the child (in the properties sheet) to gray, inheritance is broken; changes in the parent will no longer be reflected in the child. If you ever want to restore inheritance, right-click in the properties sheet, and select "restore to default".
Inheritance with Methods
With methods, the situation is slightly more complicated. Often, you want to add additional commands, but still call the default (inherited) method.
However, as soon as you type anything in the child method code, the parent method code is no longer called automatically. Please note that "Restore to default" will erase the entire code in the child method.
You solve this by explicitly calling the parent method with command DoDefault(). Often, you would place this at the beginning or at the end of the inherited method. Sometimes, you may want to conditionally call the inherited method.
VFP 3 doesn't have DoDefault(); instead, you use an operator with the queer name of "scope resolution operator", which requires specifying both the parent class and the method.
* Examples, for method Init(); parent class is cForm
* Example in VFP 5 or later:
DoDefault()
* Example in VFP 3:
cForm::Init()
From now on, I will assume that you can use DoDefault().
Please note that DoDefault() can both accept parameters (which are passed to the parent method), and return a value (the value returned by the parent method).
Easy instructions for getting into trouble
And now, finally, the fun part. Basically, I managed to get into trouble, by breaking inheritance, in four different ways. In case you ask, yes, I really did get into trouble, on different ocassions. I know how to break inheritance and how to avoid it, but it is still easy to forget some detail in method code. I believe that most programmers will use at least the first three ways to get into trouble, sooner or later.
1) The most obvious is to include code in the derived object, and simply forget DoDefault().
|