Egg or Chicken, Properties or Methods?

In Visual FoxPro you can use expressions to initialize properties. These expressions are evaluated only once when you first load a class into memory. The result is stored in the class object. To create an expression for a property, you can either enter the equals sign in the Properties Windows followed by the expression or you press the "fx" button next to the text box on the Properties Window.
If you attempt to call a method, though, you need to be aware that properties are evaluated before methods. So what does this mean? Create a new class "Level1" based on Form and store it in Level1.VCX. Add a method "CallMethod" with the following code:


Activate Screen
? "Called ", This.Class

Now add a property nTest and assign the following expression:
=This.CallMethod()*2

In the Command Window enter:

Clear All
Release All
Clear
ox = NewObject("Level1","Level1")
? ox.nTest

You notice two things. The screen is empty and nTest is .F., not 2. The reason for this is that by the time the expression is evaluated, the method code has not yet been attached to the method. CallMethod() exists, but is empty. Now let's drive this one step further. Create a program ShowInfo.prg with the following content


Lparameters toRef
? toRef.Class
toRef.CallMethod()
Return 1


Create a new class Level2 that inherits from Level1. Store the new class in Level2.vcx. Override CallMethod with this code:


Activate Screen
? "Subclass called ", This.Class

Now switch to the Command Window and enter:

Clear All
Release All
Clear
ox = NewObject("Level2","Level2")

This time you can see the following output:

Level2
Called Level2

ShowInfo is clearly called when the class is loaded. The method call also works, at least kind of. Instead of executing the code in the Level2 class it now executes the code from the Level1 class that hasn't been executed when you instantiated Level1.

What happened is that when you instantiate Level2, Visual FoxPro first creates a class object for Level1. This happens in two steps. First, all properties are evaluated. Then all methods are added. As you requested Level2, Visual FoxPro creates the class object for Level2 next. VFP does so by creating a copy of the Level1 class object including the method code. As before, properties are evaluated first. At this time, CallMethod still contains the code that has been copied over from the class object of Level1.
Only after all properties have been evaluated, Visual FoxPro adds the method code to the Level2 class object. If you create public variable in ShowInfo.prg and store toRef in that variable, you get a reference to the class object. When you execute CallMethod() on this global object after creating an instance, you get indeed the sub-classed code.

So remember: Properties exist before methods do. If you don't want to create these classes yourself, you can download them here.