GNOME Bugzilla – Bug 604299
Chained constructors: wrong initialization
Last modified: 2010-10-14 15:15:30 UTC
The following code works fine: class Test { int x; Test() {} Test.with_x(int x) { this.x=x; this(); } static int main() { var test = new Test.with_x(2); return 0; } } However, the following code gives a segmentation fault: class Test { int x; int y; Test() { y=3; } Test.with_x(int x) { this.x=x; this(); } static int main() { var test = new Test.with_x(2); return 0; } } The reason can be found in the C code: static Test* test_construct_with_x (GType object_type, gint x) { Test* self; self->priv->x = x; self = (Test*) test_construct (object_type); return self; } So, "self" is accessed before it is initialized. I believe that either: (1) self should be initialized; then the .with_x constructor code executed; then the basic constructor code. OR (2) valac should emit an error message in this case
I think there was a discussion about this problem some time ago. What I don't quite understand is the fact that Vala, being derived from C#, doesn't use the same chaining syntax, even though it fits the way this is implemented much better. As for the possibilities you are proposing, (1) is impossible in most cases. For (2), valac must enforce the chaining to be the first thing to call, which equals to the C# chaining with a bit different syntax (thus my amusement over the difference).
Thanks for the bug report. This particular bug has already been reported into our bug tracking system, but please feel free to report any further bugs you find. *** This bug has been marked as a duplicate of bug 567269 ***