Polymorphism

Hello,

In line number 24 $cast(c_tr, p_tr) is equivalent to saying c_tr = p_tr;
Why is c_tr.display() showing data=5 and id=2 ?
Since we downcasted c_tr = p_tr, c_tr should display the contents of p_tr which is data=10 and id=1

Can someone explain the reason why it displayed data=5 and id=2. ( Please don’t say it is due to Polymorphism )

class parent_trans;
  bit [31:0] data;
  int id;
  
  function void display();
    $display("Base: Value of data = %0d, id = %0d", data, id);
  endfunction
endclass

class child_trans extends parent_trans;
   
  function void display();
    $display("Child: Value of data = %0d, id = %0d", data, id);
  endfunction
endclass

module class_example;
  initial begin
    parent_trans p_tr;
    child_trans c_tr;
    c_tr = new();

    p_tr = c_tr; // or $cast(p_tr, c_tr);
    $cast(c_tr, p_tr);

    p_tr.data = 10;
    p_tr.id   = 1;
    
    c_tr.data = 5;
    c_tr.id   = 2;
    
    c_tr.display();
  end
endmodule

In reply to dvuvmsv:

It is not due to polymorphism; really it isn’t. It is because you are only constructing one object of a child_transaction class type. Upcasting or downcasting a class handle into class variables is only copying the handle, not the object.

BTW, I recommend that you don’t use the terms parent and child when talking about class inheritance. A parent and a child imply they are separate objects, but they are just different types with a base and derived relationship.

In reply to dave_59:

Hi Dave,
Even if I construct another object of p_tr by p_tr = new(), the behaviour is the same.
$cast(c_tr, p_tr) is equivalent to saying c_tr = p_tr;
c_tr should point to p_tr and should display the contents of p_tr which is data=10 and id=1
Why is it still not displaying contents of p_tr which is data=10 and id=1
Thanks,
JeffD

In reply to dvuvmsv:

Show your complete new code.

In reply to dave_59:


class parent_trans;
  bit [31:0] data;
  int id;
 
  function void display();
    $display("Base: Value of data = %0d, id = %0d", data, id);
  endfunction
endclass
 
class child_trans extends parent_trans;
 
  function void display();
    $display("Child: Value of data = %0d, id = %0d", data, id);
  endfunction
endclass
 
module class_example;
  initial begin
    parent_trans p_tr;
    child_trans c_tr;
    c_tr = new();
 
    p_tr = c_tr; // or $cast(p_tr, c_tr);
    $cast(c_tr, p_tr);
 
    p_tr.data = 10;
    p_tr.id   = 1;
 
    c_tr.data = 5;
    c_tr.id   = 2;
 
    c_tr.display();
  end
endmodule

In reply to dvuvmsv:

you need to define the function with keyword virtual in the base class