# Constructor: Member variables not visible / out of scope

**URL:** <https://discourse.julialang.org/t/constructor-member-variables-not-visible-out-of-scope/81827>\
**Category:** New to Julia\
**Tags:** constructors\
**Created:** [May 28, 2022, 9:19am UTC](https://discourse.julialang.org/t/constructor-member-variables-not-visible-out-of-scope/81827 "2022-05-28T09:19:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![DanDoe](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dandoe/32/52717_2.png) [@DanDoe](https://discourse.julialang.org/u/DanDoe)\
**Post date:** [May 28, 2022, 9:19am UTC](https://discourse.julialang.org/t/constructor-member-variables-not-visible-out-of-scope/81827/1 "2022-05-28T09:19:53Z")

</div>

In `C++` I can do the following:

```julia
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,

```julia
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:

```julia
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:

```julia
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.

---

<div class="post-metadata">

**Author:** ![skleinbo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/skleinbo/32/36080_2.png) [@skleinbo](https://discourse.julialang.org/u/skleinbo)\
**Post date:** [May 28, 2022, 9:39am UTC](https://discourse.julialang.org/t/constructor-member-variables-not-visible-out-of-scope/81827/2 "2022-05-28T09:39:42Z")

</div>

This works

> [@DanDoe](#):
>
> ```julia
> struct foo
> N::Int
> function foo(pN::Int)
> newfoo = new(pN)
> println("Hello World") # Gets printed
> println(newfoo.N) # Gets printed too
> newfoo
> end
> end
> 
> ```

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

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