ZetCode

Tcl object orientation

last modified November 24, 2026 Tcl 8.6

Tcl 8.6 includes TclOO, an object system built into the standard interpreter. It adds classes, objects, methods, inheritance and mixins without changing the command syntax: a class is a command, an object is a command, and a method call looks like a procedure call. This article builds from a single class to a small bank account hierarchy.

Creating a class

A class is defined with oo::class create, followed by a name and a body of definitions. The body is evaluated once to build the class: method defines a method, and new creates an object whose command name is returned to the caller.

classes.tcl
oo::class create Greeter {
    method greet {} {
        return "Hello there!"
    }
}

set g [Greeter new]
puts [$g greet]
puts "class: [info object class $g]"

The object is stored in g and the call is written $g greet. TclOO generates names such as ::oo::Obj12, so keep the returned name instead of building one yourself. info object class reports the class with its namespace prefix.

$ tclsh classes.tcl
Hello there!
class: ::Greeter

Constructors and destructors

A constructor runs on new and receives its arguments; a destructor runs when the object is destroyed. The variable instruction declares object variables. Without it, set inside a method creates a local variable that disappears when the method returns.

lifecycle.tcl
oo::class create Session {
    variable user

    constructor {name} {
        set user $name
        puts "opening session for $user"
    }
    destructor {
        puts "closing session for $user"
    }
    method user {} {
        return $user
    }
}

set s [Session new "jane"]
puts "user is [$s user]"
$s destroy
puts "destroyed"

The constructor stores the name in user, and the method of the same name reads it later. The destructor is the place to close files or connections. destroy deletes the object command at once. Tcl 8.6 does not call destructors for objects that still exist when the interpreter exits, so release important resources explicitly.

$ tclsh lifecycle.tcl
opening session for jane
user is jane
closing session for jane
destroyed

Methods and instance variables

Instance variables are stored per object, so two objects of one class do not share them. Methods form the public interface: callers ask for an operation instead of touching the variables. This class adds deposit and withdrawal to a balance.

account.tcl
oo::class create Account {
    variable balance

    constructor {amount} {
        set balance $amount
    }
    method deposit {amount} {
        set balance [expr {$balance + $amount}]
        return $balance
    }
    method withdraw {amount} {
        if {$amount > $balance} {
            return -code error "insufficient funds in account"
        }
        set balance [expr {$balance - $amount}]
        return $balance
    }
}

set acc [Account new 100]
puts "deposit 50:  [$acc deposit 50]"
puts "withdraw 30: [$acc withdraw 30]"

Both methods return the new balance. withdraw checks the amount and raises an error with return -code error when funds are short. The balance survives between calls because it is an object variable, not a local one.

$ tclsh account.tcl
deposit 50:  150
withdraw 30: 120

my and self

Inside a method, my calls another method on the same object, and self identifies that object. self alone is the object command, while self class is its class. Using my instead of a hard-coded object name keeps overridden methods correct.

temperature.tcl
oo::class create Temperature {
    variable celsius

    constructor {value} {
        set celsius $value
    }
    method fahrenheit {} {
        return [my toFahrenheit $celsius]
    }
    method toFahrenheit {c} {
        return [expr {$c * 9.0 / 5 + 32}]
    }
    method describe {} {
        return "[self class] reports [my fahrenheit] F"
    }
}

set t [Temperature new 100]
puts "fahrenheit: [$t fahrenheit]"
puts [$t describe]
puts "class of object: [info object class $t]"

fahrenheit delegates to toFahrenheit, and describe combines the class name with the result. The class name is stable, unlike the generated object name. A method can use my variable to declare an object variable that the class body omits.

$ tclsh temperature.tcl
fahrenheit: 212.0
::Temperature reports 212.0 F
class of object: ::Temperature

Inheritance and superclass

A class inherits from another class with a superclass instruction. The subclass receives every parent method, can add methods and can replace inherited ones. Here the base class describes a shape while the subclass supplies its own name and area.

inheritance.tcl
oo::class create Shape {
    method name {} {
        return "shape"
    }
    method area {} {
        return 0
    }
    method describe {} {
        return "[my name] with area [my area]"
    }
}

oo::class create Circle {
    superclass Shape
    variable radius

    constructor {r} {
        set radius $r
    }
    method name {} {
        return "circle"
    }
    method area {} {
        return [expr {3.14159 * $radius ** 2}]
    }
}

set c [Circle new 2]
puts [$c describe]
puts "circle is a Shape: [info object isa typeof $c Shape]"

Circle never defines describe, yet the call works: the inherited method uses my name and my area, which resolve to the versions in Circle. This late binding is the point of inheritance. info object isa typeof checks the relationship.

$ tclsh inheritance.tcl
circle with area 12.56636
circle is a Shape: 1

next

An override can keep the parent implementation by calling next, which runs the next method in the resolution order. Without arguments it passes the current arguments; with arguments it passes those instead.

next.tcl
oo::class create Shape {
    method describe {} {
        return "a shape"
    }
}

oo::class create Circle {
    superclass Shape

    method describe {} {
        return "a circle, [next]"
    }
}

oo::class create UnitCircle {
    superclass Circle

    method describe {} {
        return "a unit circle, [next]"
    }
}

set u [UnitCircle new]
puts [$u describe]
set c [Circle new]
puts [$c describe]
set s [Shape new]
puts [$s describe]

The three methods combine their text from the most specific class to the most general one. The bottom method must not call next, because doing so raises no next method implementation. The same call works in constructors: next $name $opening forwards selected arguments to the parent constructor.

$ tclsh next.tcl
a unit circle, a circle, a shape
a circle, a shape
a shape

Mixins

A mixin adds methods from another class without making it a superclass. Mixin methods win over inherited ones and do not change the object's type. oo::define attaches a mixin to a class, including its existing instances.

mixin.tcl
oo::class create Loud {
    method speak {text} {
        return "[string toupper $text]!"
    }
}

oo::class create Person {
    method speak {text} {
        return "says $text"
    }
}

oo::class create Robot {
    superclass Person
}

set p [Person new]
set r [Robot new]
puts "person: [$p speak hello]"
puts "robot:  [$r speak hello]"

oo::define Robot mixin Loud
puts "robot after mixin: [$r speak hello]"
puts "person unaffected: [$p speak hello]"

After the mixin, Robot answers with the louder version while Person is unchanged. oo::objdefine can attach a mixin to one object, and next inside a mixin continues with the class's own method.

$ tclsh mixin.tcl
person: says hello
robot:  says hello
robot after mixin: HELLO!
person unaffected: says hello

A small class hierarchy

The final example combines the ideas. Account keeps the owner and the balance and implements the common operations. SavingsAccount adds a rate, extends describe with next, and chains its constructor to the parent.

bank.tcl
oo::class create Account {
    variable owner balance

    constructor {name opening} {
        set owner $name
        set balance $opening
    }
    method deposit {amount} {
        set balance [expr {$balance + $amount}]
        return $balance
    }
    method withdraw {amount} {
        if {$amount > $balance} {
            return -code error "insufficient funds"
        }
        set balance [expr {$balance - $amount}]
        return $balance
    }
    method describe {} {
        return [format "%s: %.2f" $owner $balance]
    }
}

oo::class create SavingsAccount {
    superclass Account
    variable balance rate

    constructor {name opening annual} {
        next $name $opening
        set rate $annual
    }
    method addInterest {} {
        set balance [expr {$balance * (1 + $rate)}]
        return $balance
    }
    method describe {} {
        return "[next] (savings, [format %.0f%% [expr {$rate * 100}]])"
    }
}

set acc [SavingsAccount new "jane" 1000 0.03]
$acc addInterest
puts [$acc describe]
puts "withdraw 30: [$acc withdraw 30]"

The account earns three percent through addInterest and is described through the method it inherits and extends. describe calls next and appends the type. The base class handles the withdrawal. The subclass declares balance again because a method may only use an object variable that its own class has declared.

$ tclsh bank.tcl
jane: 1030.00 (savings, 3%)
withdraw 30: 1000.0

Source

TclOO has its own command pages in the Tcl 8.6 manual. They cover the class, object and define commands used here, and the three commands that appear inside methods.

This article built a class from scratch, added constructors and instance variables, then used my, self, inheritance, next and mixins in a small hierarchy. The Tcl namespace command explains the machinery behind class names, and Tcl proc command shows the plain procedure that a method is built on.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.