Constructors #2426
Replies: 1 comment 1 reply
-
Any keyword spelling risks colliding with identifier names, and we specifically don't want to go down the See p0257 for a discussion of the problems that we're trying to avoid by not having constructors. |
Beta Was this translation helpful? Give feedback.
-
Currently Carbon has only one way to construct class instances which uses braces with all the fields explicitly defined.
For example:
class Foo {
var x: i32;
var y: i32;
}
var origin: Foo = {.x = 0, .y = 0};
In particularly, this is used by factory functions:
class Foo {
var x: i32;
var y: i32;
fn CreateOrigin() -> Self {
return {.x = 0, .y = 0};
}
}
When it comes to derived class, the syntax is, for example:
class Bar extends Foo {
var z: i32;
fn CreateBarOrigin() -> Self {
return {.base = Foo.CreateOrigin(), .z = 0};
}
}
I find the keyword base a little bit confusing and, on top of that, it forbids the definition of a field named base (which is quite an usual name).
One alternative would be to instead write something like:
return {... Foo.CreateOrigin(), .z = 0};
Where the three dots means the base class.
From my point of view, having constructors (on top of field initialization) could be useful (especially when a class has a lot of fields).
class Foo {
var x: i32;
var y: i32;
constructor[me: Self](x: i32, y: i32) {
me.x = x;
me.y = y;
}
}
For a derived class we could use a C++ like syntax:
Bar.constructor[me: Self](x: i32, y: i32, z: i32)
: Foo{x, y} {
me.z = z;
}
Or a syntax which allows some computation before the base class construction:
Bar.constructor[me: Self](x: i32, y: i32, z: i32)
const new_x = x * scale;
const new_y = y * scale;
…{new_x, new_y};
me.z = z * scale;
}
Where the three dots mean access to the base class’ (here Foo) constructor.
Beta Was this translation helpful? Give feedback.
All reactions