Thursday, July 21, 2016

inheritance -- an interesting example

When a derived class inherits properties from its base class and derived class has its own properties with same name, then there will be 2 copies of those properties.
If you take a below example, class b will have 2 copies of the variable enable. So it wont print the display since the object B will be able to access derived class version of 'enable' variable and the function 'abc' checks the base class version of 'enable' variable.

class a;
bit enable;
virtual function void abc();
  if(enable)
  $display("ABC enable=%0d",enable);
endfunction
endclass

class b extends a;
bit enable;
endclass

module m;
a A;
b B,ba;
initial begin
  A=new();
  B=new();
  A.enable=1;
  B.enable=1;
  B.abc();
end

endmodule


How to fix this? 
1. Use the base class object(A) point to derived class object(B) and set the base version of 'enable' variable. Now if you call B.abc(), it will print. 

class a;
bit enable;
virtual function void abc();
  if(enable)
  $display("ABC enable=%0d",enable);
endfunction
endclass

class b extends a;
bit enable;
endclass

module m;
a A;
b B,ba;
initial begin
  B=new();
  A = B;    
  A.enable=1;
  B.enable=1;
  B.abc();
end
endmodule


2. Another solution is using static variable. Here the beauty is you don't even need to create an object of base class. 

class a;
static bit enable;
virtual function void abc();
  if(enable)
  $display("ABC enable=%0d",enable);
endfunction
endclass

class b extends a;
bit enable;
endclass

module m;
a A;
b B,ba;
initial begin
   B=new();
  A.enable=1;
  B.enable=1;
  B.abc();
end
endmodule




No comments:

Post a Comment