Is there a way to make a class variable visible but constant to outsiders, but changeable (mutable) to the class itself?

vit via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 21 11:25:03 PDT 2016


On Saturday, 21 May 2016 at 17:32:47 UTC, dan wrote:
> Is it possible to have a class which has a variable which can 
> be seen from the outside, but which can only be modified from 
> the inside?
>
> Something like:
>
> class C {
>   int my_var = 3;     // semi_const??
>   void do_something() { my_var = 4; }
> }
>
> And then in another file
>
> auto c = new C();
> c.my_var = 5; // <<<- should trigger a compile-time error
> writeln("the value is ", c.my_var);  // <<<- should print 3
> c.do_something();
> writeln("the value is ", c.my_var);  // <<<- should print 4
>
> Reading Alexandrescu's book suggests the answer is "no" (the 
> only relevant type qualifiers are private, package, protected, 
> public, and export, and none seem appropriate).
>
> (This effect could be simulated by making my_var into a 
> function, but i don't want to do that.)
>
> TIA for any info!
>
> dan

class C {
	private:
		int my_var_ = 3;     // semi_const
		
		@property final void my_var(int x){	///private setter
			this.my_var_ = x;
		}
		
	public:
		@property final int my_var()const{	///public getter
			return my_var_;
		}
		
		void do_something() {
			my_var = 4;
		}
}


More information about the Digitalmars-d-learn mailing list