title: Returning pointer to intent(in) argument
body: <p>I try to better understand the difference between <code>const</code> from C/C++ and <code>intent(in)</code> in Fortran in the context of classes.</p>
  <p><strong>C++</strong>:
  If I <code>const</code> the implicit <code>this</code> argument to a member function and I return references to members of <code>this</code>, these references have to be <code>const T*</code>.
  So the <code>const</code> does not only apply to the scope of the function call, but also extends to all references &quot;created&quot; in that function call.</p>
  <p><strong>Fortran</strong>: If I <code>intent(in)</code> the <code>this</code> argument of a member function the <code>intent(in)</code> only applies to the scope of the member function. I cannot mutate <code>this</code> inside the member function, but I can return a reference and modify <code>this</code> outside.</p>
  <p>If I have the following more or less equivalent code for a Counter class in Fortran and C++ to test this and it seems to be correct.</p>
  <pre><code>#include &lt;iostream&gt;
  
  
  class Counter {
      int val{};
  
  public:
      auto next()
      {
          return val++;
      };
  
      const auto raw() const
      {
          const auto ptr = &amp;val;
          return ptr;
      };
  };
  
  int main()
  {
      Counter c{};
      std::cout &lt;&lt; c.next() &lt;&lt; &quot;\n&quot;;
      std::cout &lt;&lt; c.next() &lt;&lt; &quot;\n&quot;;
  
      auto ptr = c.raw();
      // does not compile, as it is expected
      *ptr = 0;
      std::cout &lt;&lt; c.next() &lt;&lt; &quot;\n&quot;;
  
      return 0;
  }
  </code></pre>
  <pre><code>module counter_mod
      implicit none(type, external)
      private
      public :: Counter_t
  
      type :: Counter_t
          private
          integer :: val = 0
      contains
          procedure :: next
          procedure :: raw
      end type
  
  contains
  
      integer function next(this)
          class(Counter_t), intent(inout) :: this
          next = this%val
          this%val = this%val + 1
      end function
  
      function raw(this) result(res)
          class(Counter_t), target, intent(in) :: this
          integer, pointer :: res
          ! This would be forbidden
          ! this%val = 5
          res =&gt; this%val
      end function
  end module
  
  program test_raw
      use counter_mod, only: Counter_t
      implicit none(type, external)
  
      type(Counter_t), target :: c
      integer, pointer :: ptr
  
      write(*, *) c%next()
      write(*, *) c%next()
  
      ptr =&gt; c%raw()
      ptr = 0
      write(*, *) c%next()
  end program
  </code></pre>