Chuck constructors and inheritance
07.01.15
So there are no constructors in Chuck (using v1.3.2.0). No worries, let's find a quick workaround: let's create an init() method that we call right after instantiation.
class Test { fun void init() {} fun void init(int i) { // do something with i } } Test t; t.init(3);
And they can be overloaded, sweet. But, here's obstacle 2 (yes, obstacle 1 was not having constructors in the first place!): there's no way to call the parent's constructor. So:
class TestChild extends Test { fun void init(int i) { // I can overwrite the parent's init method // but I cannot call it from here. // super.init(i) would be nice! } }
So now what? One option is to be more verbose with the method names, and have Test.initTest() and TestChild.initTestChild(). Then I could call initTest from initTestChild. But this kind of ugly.
And then I thouhgt: what if I use static methods? This makes it way less elegant, but it might solve the inheritance issue! Something like:
class Test { fun static void init(Test theObject) { // constructor without arguments, might still do some work } fun static void init(Test theObject, int i) { // do something with i } } class TestChild extends Test { fun static void init(TestChild theObject, int i) { // Call the parent's constructor! Test.init(theObject, i); // do something with i, if you want } } Test t; Test.init(t); TestChild tch; TestChild.init(tch);
This works! Admittedly it's not the cleanest solution, but it solves the problem... well, here comes obstacle 3: static methods are not inherited. That was a weird bug that took a while to find. So this looks like it should work:
TestChild tch; TestChild.init();
But I get a funky error, "Assertion failed: (func != NULL), function emit_engine_emit_exp_dot_member, file chuck_emit.cpp, line 3416". I can overwrite init() in TestChild and call Test.init from there, but this means that I'd have to overwrite *all* init methods in all subclasses, not an option!
So close... It looks like calling the parent constructor won't happen for now, which might be a good thing since this solution already seemed a bit convoluted and tedious to implement. It was fun giving it a go though. :)
0 comments
Add a comment
PS: no links allowed in comment.