Is it possible to "overload" based on visibility?

60rntogo 60rntogo at gmail.com
Wed Sep 23 18:38:53 UTC 2020


There are really two questions here, one that I intended to ask 
and one that came out while I was trying to figure out the 
answer. Consider this simple code:

---
module foo;

struct Foo
{
   private int _x;

   int x() const
   {
     return _x;
   }
}
---

If I have an instance of Foo outside of the module I can read the 
value of _x using the property method x, but I can only modify it 
from inside the module using the name _x. This is exactly the 
kind of encapsulation that I often want, but I'm wondering if 
this could be improved a little.

It would be nice if I didn't have to remember if I need to use _x 
or x depending on the context. Instead I would like to use only 
one name, say x, from both inside and outside of the module and 
have compiler complain if I'm trying to modify it from the 
outside.

My naive attempt was this:

---
import std : writeln;

private int _x;

private ref int x() return
{
   writeln("ref int");
   return _x;
}

int x() const
{
   writeln("int");
   return _x;
}
---

At first I didn't even expect this to compile, but it does and I 
can call these methods. I believe an overload is chosen based on 
the type qualifier of a Foo instance. What is truly unexpected is 
that if I call x on a mutable object even outside of the module, 
then the first overload is called!

So my questions are:

1. Can I achieve my original goal of being able to refer to _x by 
one name, so that I have read only access from outside the module 
and read/write access from inside?
2. Is the behavior that allows me to call the private method 
intended? This is such a blatant violation of encapsulation that 
it feels like a bug either in the language or the implementation.


More information about the Digitalmars-d-learn mailing list