carbon-lang icon indicating copy to clipboard operation
carbon-lang copied to clipboard

Should an adapter have access to `protected` fields of its adapted type?

Open zygoloid opened this issue 1 year ago • 1 comments
trafficstars

Should this be valid:

class A {
  protected var a: i32;
}
class B {
  extend adapt A;
  fn F[self: Self]() -> i32 { return self.a; }
}

On the one hand, adapting a class is somewhat like inheritance, so perhaps an adapter should be able to access protected fields. On the other hand, adapting a class is not inheritance in various ways. Note that A is a final class; if it inherited a from one of its base classes, it may not expect that any code outside A and its base class can access that field. (Maybe we might even want to reject protected members in final classes.)

If we don't allow this, one could still use friend declarations to allow specific adapters to access non-public class members. The design currently doesn't permit adapters to access protected members of the adapted type; this came up because the toolchain currently does (though we plan to change it to match the current design).

zygoloid avatar Nov 20 '24 23:11 zygoloid

I suggest that the answer should be "no" for now.

I think today, the only coherent model and principle of design we have for protected is the one that only really applies to inheritance and comes from C++. We shouldn't IMO incrementally extend this model at this point.


I do think there are good use cases, and maybe use cases that friend in its current form doesn't address. But I think we should look at those and come up with a new tool for them. When we do, we should look and see if it could also address the use cases for protected, as it would be nice to have a single more general tool.

Only if the answer is "yes" should we consider re-using the term protected for this new model. And I think we should be somewhat reluctant to do so and mildly prefer a fresh term to avoid confusion with C++'s protected.

But all of that is for the future. Until we're in a place to dig into that model design, I'd say keep protected narrow and focused on inheritance.

chandlerc avatar Nov 26 '24 00:11 chandlerc