Version 1 of itcl::class

Updated 2006-07-15 14:07:15

A class resembles the C++ class. That is it consists of a collection of data and methods (C++ Member Functions).

Code using an itcl class may have multiple instances of a class (there may be several different people with several bank accounts each - a person and a bank account would be 2 sensible classes to define).

  package require Itcl
  itcl::class helloworld {
    public variable owner "No-one"

    method greet {} { puts "Hello World from $owner" }
  }
  helloworld  h1
  helloworld  h2
  h1 greet
  h1 configure -owner Me
  h2 configure -owner You
  h1 greet
  h2 greet

Creates 2 helloworld objects (h1 & h2). By default they respond with the name "No-One" when the method greet is called.

You can set public variables of the class using the configure command as above; variables are private by default (but can also be of type 'protected'). Private variables often employ code like this:

  package require Itcl
  itcl::class helloworld {
    private variable owner "No-one"

    method setowner {nuowner} { set owner $nuowner}
    method getowner { } { return $owner }
    method greet {} { puts "Hello World from $owner" }
  }
  helloworld  h1
  helloworld  h2
  h1 setowner  Me
  h2 setowner  You
  h1 greet
  h2 greet

The class can also have a constructor & destructor method, and can refer to itself by the $this variable.

  package require Itcl
  itcl::class helloworld {
    public variable owner "No-one"
    constructor {} {puts "helloworld object $this has been created"}
    destructor { puts "$this is deleted - you should delete any dynamically allocated items here"}

    method greet {} { puts "Hello World from $owner" }
  }
  helloworld h1
  h1 greet
  itcl::delete object h1
  h1 greet ;# will return an error "invalid command name "h1"" since h1 has been deleted.

Well that is a basic guide to classes. More to follow!