Clarify object allocation in sv

Hi,

class base;
  int N = 3; 
  function int get_N(); 
    return N; 
  endfunction 
endclass 

class ext extends base; 
int N = 4; 

function int get_N(); 
  return N; 
endfunction 


module main; 
  initial 
    begin 
      ext e = new;
      base b =e; 
      $display(b.get_N()); // "3" 
      $display(e.get_N()); // "4" 
    end
endmodule 

In above program
1.base class and extended classes having methods with same signature but my problem is actually here i created object for extended class only and i passed extended class obj handle to base class. as per my understanding after passing handle it should point to extended class memory but when i invoke methods of base class how it is able to find base class methods without creating object of base class.

This seems like improper use of inheritance.

Normally when you extend a class, you add class properties and non-virtual methods with different names. You use the same name in the extended class when you want to hide the base class property or virtual method from access within the extended class. (And I would say that it is a very bad practice to give an extended class property the same name as a base class property - it will create havoc).

If you have a purpose in mind for using the same name, please explain further.

I agree with Dave,writing code in the above manner would create havoc.

However, to answer your question,

  1. Even though you haven’t created object of base class there would be memory allocated for members of base class within the extended class.
  2. Since you are trying to access using base class handle, it would consider the objects within the extended class memory as if it is base class. Hence, you are seeing features of base class when called using handle of base class for extended class object.

In reply to Ashith:

Hi Kumar,

I am bit confused and not convinced with your answer.

1.In above example, the method of base class override with the new implementation of method in extended class. In this case original method which is copied from base class is no longer available in extended class.
2.How it is able to find base class method when we pass extended handle to base handle without creating object of base class?

If any mistakes in formation kindly excuse me.

In reply to sivakrishna:

Yes the task has been overriden, but overriden with the same method. But for the base class handle N is a different variable as compared to extended class.

Note: Not sure if this is tool specific.

Hi shivkrishna,

1.In above example, the method of base class override with the new implementation of method in extended class. In this case original method which is copied from base class is no longer available in extended class.
Karthik: In above example ext class didn’t override base class method. To override base method, declare base method with virtual.

Thanks,
G.karthik