Constructor: Member variables not visible / out of scope

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.

This works

Most importantly, the constructor must return the instance created by new.

Your last example results in infinite recursion, because the constructor keeps calling itself.

2 Likes