Why base class can't be assigned to derived class?

Hi,

Why base class can’t be assigned to derived class?

class A;
  bit var1;
endclass

class B extends A;
  //No Variables defined 
endclass

module top;
  A a =new();
  B b =new();
  initial
    b = a; // Compilation error
endmodule

In reply to SMS:


class A; // Base class
  bit var1;
endclass
 
class B extends A;
  bit b1;
endclass
 
module top;
  A a =new();  // pointer to base 
  B b =new(); // pointer to B, with access to a vars 
  initial begin 
    b = a; // Compilation error
          // if it were legal, then b points to the base class A
    b.b1=1'b1; // There would be no "b1" since the pointer b has no access to 
               // the variables in class b (b pointer is to the base class)     
  end 
endmodule

Ben SystemVerilog.us

In reply to ben@SystemVerilog.us:

Thanks Ben,

My Query relates to the inheritance concept of OOPs.

If no extra properties defined in derived class, why compiler still complains about legal assignment.

class A;
  bit var1;
endclass
 
class B extends A;
  
endclass
 
module top;
  A a =new();
  B b =new();
  initial
    b = a; // Compilation error
endmodule

–SMS

In reply to SMS:

Because assignment type compatibility rules are based on name of the type alone, not on the contents of the type. That keeps the rules simple and manageable. It’s no different if you had:

class A;
  bit var1;
endclass
class B;
  bit var1;
endclass
module top;
  A a =new();
  B b =new();
  initial
    b = a; // Compilation error
endmodule

Thanks Dave.

When derived class assigned to base class, hope same rule applicable, then why tool not issuing any error.

class A;
  bit var1;
endclass

class B;
  bit var1;
endclass

module top;
  A a =new();
  B b =new();
  initial
    a = b; // No Compilation error
endmodule

In reply to SMS:

Maybe that was a bit too simple. The key point you don’t look at the contents of a class type definition for compatibility.