Search | Synergex.com | Contact Us | Resource Center Login | Home|
News

What is the output of the following program?

namespace kitchen
  class pantry
    public virtual  property thyme, i
      method get
      proc
      mreturn  m_thyme
      end
      method set
      proc
      m_thyme =  value
      end
    endproperty
    protected  m_thyme, integer
  endclass
  class fund  extends pantry
       
    public override  property thyme, i
      method get
      proc
      mreturn 0
      end
    endproperty
  endclass
endnamespace
main
record
      spice_rack  ,@pantry
proc
      open(1,o,"TT:")
      spice_rack =  new fund()
      spice_rack.thyme  = 2
      spice_rack.thyme  = spice_rack.thyme + 5
      writes(1,string(spice_rack.thyme))
end
 

a. 7
b. 5
c. 0
d. A runtime error
e. This does not compile

Answer

This program creates an instance of the "fund" class and stores it in the variable "spice_rack," which is declared as being of the "pantry" class. This is legal because "fund" is derived from "pantry."

The "pantry" class has a property named "thyme."  The "fund" class overrides this property, but only provides a "get" method.  Thus, at compile time, if a variable of type "fund" attempts to write to that property, a compilation error would occur (e).  However, since the variable is declared as "pantry" (which does have a "set" method for the property), this code is allowed.

Following the behavior of other similar languages like C#, Synergy does not throw an exception at runtime in this case (d).  Instead, it uses the "pantry" method when setting the property, and the "fund" method when getting it.

Thus, the first assignment of 2 to the property causes the protected member m_thyme to contain the value 2.  The next statement attempts to add 5 to the value of the property, so you might think that m_thyme would then contain the value of 7 (a).  But remember that the "get" will use the override method from "fund,' which returns 0.  Thus, 5 is added to 0 and results in 5 in m_thyme (b).

The final statement invokes the "get" method again, which again returns 0.  Which goes to show that thyme flies when you're having fund. Thus, (c) is the correct answer.

This example demonstrates the power of override properties in Synergy, but also their dangers.  When overriding a property, if you don't override both its "get" and "set" methods, make sure that they are compatible with the idea of setting and retrieving the same value.