Version 2 of Automatic get/set methods for an itcl class

Updated 2007-02-12 13:13:54

As the itcl::class is a tcl command, you can insert code into the class declaration. It is common C++ practice to have set/get methods to protect the variables in an object from manipulation outside the class. This sample class creates a set of methods to set and enquire a list of protected variables.

  console show
  package require Itcl
  itcl::class tclass {
      foreach v {time distance} { 
        method get$v {} [subst -nocommands { return [subst $$v] }]
        method set$v nuval [subst -nocommands { set $v \$nuval } ]
        protected variable $v "Var $v"
      }
      constructor {} { puts "Constructs $this" }
      method speed {} { return [expr {[getdistance]/[gettime]}]}
  }
  tclass a
  a setdistance 2
  a settime 3.0
  puts "Travelled [a getdistance] taking Time [a gettime] so speed is [a speed]"

The variable list can be arbitrarily long of course when this would save considerable typing and validation effort. The code can include any of the itcl::class constructs. If you wish the variable list to be a variable in the class then it must be a common variable so that it is available at class creation time:

  itcl::class tclas2 {
      common vars {time distance power}
      foreach v $vars { 
        method get$v {} [subst -nocommands { return [subst $$v] }]
        method set$v nuval [subst -nocommands { set $v \$nuval } ]
        protected variable $v "Var $v"
      }
      constructor {} { puts "Constructs tclas2 $this" }
      method showVarsandMethods {} { puts "Variables with get/set methods exist for: $vars.\nMethods are: [info function]" }
  }
  tclas2 b
  b showVarsandMethods 

This example shows that setpower, getpower, set/getdistance and set/gettime are all methods of the class tclas2 even though the functions are not explicitly declared.

Entered by GWM.