Polymorphism

Hi All,

I am trying to execute the code to understand polymorphism in SV, but not receiving the expected output;

class c1;
   virtual function void f1 ();
    $display("ADD_FUNCTION");
   endfunction
endclass

class c2 extends c1;
   function void f2 ();
    $display("MUL_FUNCTION");
  endfunction
endclass

module poly_ex();

c1 obj1;
c2 obj2;
  
  initial begin
    obj1 = new();
    obj1.f1();
    
    obj2 = new();
    obj1 = obj2;
    obj1.f1();
    
  end
endmodule

///////////////////////
Expected output;
ADD_FUNCTION
MUL_FUNCTION

Actual output;
ADD_FUNCTION
ADD_FUNCTION

In reply to Mahesh K:

Function f1 is never overriden. Even after handle assignment base object is made to call f1 which is only in base class which displays ADD_FUNCTION.Instead f2 write f1 in extended class for polymorphism.

In reply to svats:

It means, methods should have the same name in both base class and extended class in order to achieve polymorphism ?
Is that the only solution ?

In reply to Mahesh K:

Yes same name with virtual keyword in base class.

You achieve polymorphism by redefining ( read : overriding ) the behavior (read: method) of the base/super class.
Here if you are trying to redefine/override the behavior (f1) of the class C1, you will have to override the same behavior ( f1 ) in the extended class.

Thank you all :)
Understood.