Why is my code not failing when accessing non static method from not static class?

Hi,

In class_B I am accessing non-static method from non-static class_A. I have not "new"d class_A in class_B. How is my code working without fail? I want to understand the background concept. Please help- Thx.

module top();

class class_A;
  function void compare( int a1, int a2);

      if(a1 > a2)
         $display("%d  > %d\n",a1,a2);
      if(a1 < a2)
         $display("%d  < %d\n",a1,a2);
      if(a1 == a2)
         $display("%d  ==  %d\n",a1,a2);

  endfunction
endclass

class class_B;

   class_A  A;

   //function calling class_A's comapre function
   function void new_compare(int a , int b);;
      A.compare(a,b);
   endfunction

endclass

 //class B instance
  class_B  B;

  initial begin

     $display("Start Test\n");
     B = new;
     B.new_compare(32,24);

  end


endmodule : top

Your code “works” because the method class_A::compare makes no references to any non-static class properties. Most implementations add an implicit this handle argument to non-static class methods, and it would not be until the method tries to reference the null this handle that you would see an error. However, the LRM does not guarantee this behavior and you should declare compare() as a static method so the compiler will check that compare does not access any non-static class properties.

Accessing non-static members (see 8.9) or virtual methods (see 8.20) via a null object handle is illegal. The result of an illegal access via a null object is indeterminate, and implementations may issue an error.

module
 class myclass
  int A=1;
  function void print;
     $display(A);
  endfunction
 endclass

myclass h;
initial begin
        h = new;
        h.print;
        end
endmodule

The above code is usually implemented as

module
 class myclass
  int A=1;
 endclass
 function void my_class_print(myclass this);
     $display(this.A);
  endfunction

myclass h;
initial begin
        h = new;
        myclass_print(h);
        end
endmodule

In reply to dave_59:

Got it! Thank you Dave for taking time to answer the question.

In reply to srividya2u:

I think this is tool implementation specific. I tired to run the same code on VCS and it gave error:
Error-[NOA] Null object access
oops1.sv, 17
The object is being used before it was constructed/allocated.
Please make sure that the object is newed before using it.

#0 in \class_B::new_compare at oops1.sv:17
#1 in unnamed$$_1 at oops1.sv:26
#2 in top

In reply to srramas:

As I said earlier, the LRM does not specify the behavior of a null access. You could either new the object first, or declare the method as static.