https://toitlang.org/ logo
How to call a function of the base class?
# help
k
If a derived class and its base class have both the same function implemented. But if the base calls its function the function of the derived class is executed. How can I force to call the base class function ?
f
You can call
super
. example:
Copy code
class A:
  foo x:
    print "from A: $x"

class B extends A:
  foo x:
    super (x + 1)
k
Copy code
class Base:
  f m/string: print "Base: $m"
  b:   f "b"

class Derived extends Base:
  f m/string: print "Derived: $m"
  d: b

main:
  c := Derived
  c.d
What I expected is that b calls Base, but what is get is "Derived"
class A can't know that it is derived.
f
every call in Toit is virtual, except for direct
super
calls.
Extending classes is one of the most tight ways of binding two different classes. It should be done with care.
this is just one example, but there are many others, where changing the base or derived class can lead to unexpected behavior.
k
Aha: i use the function to log things. And now wondered that always the derived log-ID appears.
f
๐Ÿ™‚
k
every call in Toit is virtual that is new for me and now the behaviour makes sense. Thank you
I need to read a language concept doc ...
k
You could make the
f
functions static?
Copy code
class Base:
  static f m/string: print "Base: $m"
  b: f "b"

class Derived extends Base:
  static f m/string: print "Derived: $m"
  d: b

main:
  c := Derived
  c.d
... and except for calls to top-level or static functions.
The downside to making these static is that you have to pass the instance (
this
) to
f
if you want to access the instance from within
f
.
k
Thank you. Where can I find the holy toit bible ๐Ÿ˜‡ ?
f
Some of it is here: https://docs.toit.io/language Probably still some things missing. The object model is also relatively similar to Java's and/or Dart's.
k
I drink coffee and I play darts ๐Ÿคช grew up reading books (Kernighan, Ritchy, Stroustrup) ๐Ÿค“
f
Java, C#, Dart, and Toit all have pretty similar (core) object models.
With time, they add more features (extension methods, ...), but at their core they still are the same: classes with interfaces, and all method calls are virtual.
k
...and the way (making you happy) to program ยตC's is Toit!
3 Views