Updated 2012-09-08 16:27:05 by LkpPo

GWM In an itcl class, all instances of a class share the same variable for any variable declared common. That is changing a common variable in one class instance changes the value for all class instances.

Common variables are created (and can be used) at the time that the class is declared.
  package require Itcl
  itcl::class test {
    common v1 0
    common v2 0
      puts "Initial v1 and v2 for class test is $v1 $v2"
    method setv1 {v} { set v1 $v }
    method setv2 {v} { set v2 $v }
    method showvalues {} { puts "$this has commmon values $v1 $v2" }
  test a
  test b
  b setv1 2
  b showvalues
  a showvalues
  # then set v2 via the a object
  a setv2 3.14
  b showvalues
  a showvalues

Both a and b report the same values for v1 and v2 regardless of which object was used to set the value.

GWM Jul 2007 Note that common variables could slow down your object construction. This is because (as suggested in Tcl help) the common variables are reinitialised every time a new object is created. The following constructor shows an alternative which only constructs the parms variable the first time a sample object is created:
  package require Itcl
  itcl::class sample {
    common parms
    constructor {} {
     if {![info exist parms]} {
       puts "$this initialise common parms"
       foreach {pv} {{p1 2}     {p3 3} } {
         lappend parms $pv
     } else {
       puts "$this parms common already exists $parms"
  sample a
  sample b
  sample c

gives the response:
  ::a initialise common parms
  ::b parms common already exists {p1 2} {p3 3}
  ::c parms common already exists {p1 2} {p3 3}

Showing that the initialisation only occurs once and that later created objects share the same parms values. I found one complex program which took half the time to initialise with this construction. A retest with simpler timing showed that including the if {![info exist parms]} is slower (about 10% for 10000 objects) in the above code, so I am not sure where the extra time came from.

Googie 17-07-2007 - How could they (common variables) be reinitialised every time, if common variable has to contain common value? Every new initialisation would overwrite previous value, wouldn't it?