Suppose the following code declarations:
itcl::class ObjectA {
private variable m_ownedObject
private variable m_someVariable
constructor {} \
{
set m_ownedObject [ObjectA #auto]
}
protected method SetSomeVariable {newVal} {
set m_someVariable $newVal
}
public method SomeMethod{} {
$m_ownedObject SetSomeVariable 5
}
}
This is the only way I know how to modify m_someVariable from within SomeMethod on m_ownedObject. In other languages (say C/C++/C#/Java to name a few), I’m pretty sure I could just say something like:
m_ownedObject.m_someVariable = 5
Is there a way to do something like this in tcl, or do I always need to create protected getters and setters? Hopefully this is reasonably clear.
You cannot directly do what you’re asking for in itcl. However, this being Tcl, you can work around that, and directly set the member variable from anywhere. I use a helper routine called
memvwhich you pass an instance and a variable name, and it returns a “reference” to that variable.This obviously bypasses the private/protected mechanisms that Itcl set up, so you’re violating abstractions using them. It’s your call whether you want to use it. I find it invaluable for debugging, but don’t it in production code.
The example usage is:
The code for
memvis:Similarly, I have a helper routine named
memvwhich allows you to call any method (including private and protected methods). It’s usage is similarAnd it’s code is: