Help needed regarding visibility

i was testing with class instantiation and everything worked until i tried to implement

public var total = add();

and came to an error regarding the call to add() function :
Cannot access this or other member field in variable initialization
according to my understanding of visibility, private function add() and variables a and b should be accessible to the call in the same class, so im kinda confused. any help is appreciated!

class Main{
  static function main() {
    var ans = new X(5,6);
   trace(ans.total);
  
    
}
}
class X{

var a:Int;
var b:Int;
public var total = add();
public function new(a,b)
  {
  this.a=a;
  this.b=b;
}
function add()
  {
  return a+b;
}


}


Well, there’s nothing more to tell :slight_smile:
It’s not about visibility. Haxe just doesn’t allow to use any instance fields or this in init expressions of instance vars.
Instead of

public var total = add();
public function new(a,b)
  {
  this.a=a;
  this.b=b;
}

you have to do

public var total = add();
public function new(a,b)
  {
  this.a=a;
  this.b=b;
  this.total = add();
}

Assuming you meant something like this?

public var total:Int
public function new(a,b)
{
  this.a=a;
  this.b=b;
  this.total = add();
}

Yes. You’re right.

thanks, it worked! i was following the haxe cookbook where there was only one class and didnt realize the extra step.

You could also use a getter.

class Test{
	static function main() {
    	var ans = new X(5,6);
   		trace(ans.total);
    }
}
class X{
	var a: Int;
	var b: Int;
	public var total( get, never ): Int;
	public function get_total(){
        return a+b;
	}
    public function new(a_,b_){
      a=a_;
      b=b_;
	}
}

thanks will look into it

Note that a getter has different semantics here because the value is calculated on every access, which may or may not be what you want.