Julia Constructors: Member variables not visible / out of scope in constructor

100 Views Asked by At

In C++ I can do the following:

class foo { 
private:
   int N;
public:
  foo(const int pN) {
    N = pN;
    std::cout << N << std::endl;
  }
};

or, with the concept of outer constructors in Julia in mind,

class foo { 
private:
   int N;
};

foo::foo(const int pN) {
    N = pN;
    std::cout << N << std::endl;
}

Can you do the same in Julia, i.e., set some member variables and then do something with them? Consider the MWE below:

struct foo
  N::Int
  function foo(pN::Int)
    new(pN)
    println("Hello World") # Gets printed
    println(N) # ERROR: LoadError: UndefVarError: N not defined
  end
end

Why is that and how do I deal with this?

Even more strange is the behaviour for outer constructors:

struct foo
    N::Int
  end 

function foo(pN::Int)
  println("Hello World") # Not shown
  foo(pN)
  println("Hello World") # Not shown
  println(N) # No error
end

although I get the warning that the outer constructor overwrites the "default" one - so I suspected that I would at least see something, either print message or Error.

1

There are 1 best solutions below

1
On

There is no scope. Julia does not have object oriented programming facilities. Store the result of new as self and access the value of N as a field of self.

julia> struct foo
           N::Int
           function foo(pN::Int)
               self = new(pN)
               println("Hello World")
               println(self.N)
               self
           end
       end

julia> foo(5)
Hello World
foo(5)

Your second example results in a stack overflow.