How parent class variable got memory because variable get memory only when object is created

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 
   
   function int get_N1(); 
      return super.N; 
   endfunction 
endclass 

module main; 
      ext e;
      base b;
         
        initial begin 
         ext e     = new(); 
         base b = e; // parent pointing to same child object! 
         $display("b = %d", b.N);  // "3"   //call parent function because its not virtual.
         $display(b.get_N());    // "3"   //call parent function because its not virtual.
         $display(e.get_N());    // "4" 
         $display(e.get_N1());   // "3" - super.N 
      end 
endmodule

Q1) how parent class variable got memory because variable get memory only when object is created.

Q2) If parent is pointing to child then how its printing parent class variable, it should access child variable. (b.N)

Using “parent” and “child” terminology is misleading when referring to inheritance. Constructing an extended object inherits all the properties of the base class-- there is only one object. When you use the base class variable b, you can only access the non-virtual properties defined by the base class type. The extended properties are still there.

Hi Dave,

Sorry I got confused with the statement. Can you please confirm my understanding that variables will get memory only when object is created.
If this understanding is correct, then how the parent variable is accessed by using b.N.

When constructing ext e = new();, the memory for two class member variables gets allocated, base::N and ext::N.

You cannot access the ext::N from b.N.

  • All classes have a default constructor if no explicit constructor is defined.
  • The new() method of the child class automatically invokes the new() method of its parent class first, ensuring that the parent class is properly initialized before the child class.