Itcl common inheritance

GWM Common variables Itcl common variables have a slightly unexpected behaviour when used in inherited classes. If a class inherits from another class and also declares the same common variable name then the default value from the base class is used. Both classes (and all objects of those classes) share exactly the same common variable (v1 in this example).

This could be a "gotcha" if you are expecting test2 objects to have the specified initial value.

  package require Itcl
 # test inherited commons
  itcl::class test {
    common v1 "test default"
    constructor {} {
      puts "Initial v1 for class test is $v1"
    }
    method setv1 {v} {set v1 $v}
    method showvalues {} { puts "$this has commmon value $v1" }
  }
  itcl::class test2 {
   inherit test
    set v1 "Test2 default value"
   constructor {} {
      puts "Initial v1 for class test2 is $v1"
  }
 }
  eval {
    test a
    test2 b
    puts "although v1 defines a default value in class test2, the value from the inherited class test is used"
    a showvalues
    b showvalues
    puts "modify the common variable in a and the inherited class is also affected"
    a setv1 2
    a showvalues
    b showvalues
    puts "then set v1 via the b object"
    b setv1 3.14
    a showvalues
    b showvalues
  }