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.
There is no scope. Julia does not have object oriented programming facilities. Store the result of
new
asself
and access the value ofN
as a field ofself
.Your second example results in a stack overflow.