The typedef construct allows you to create type aliases for various data types, including classes. Using typedef with classes simplifies code management, improves readability, and promotes modular design.
In System Verilog, there are scenarios where a class handle of another class is required before the actual class definition is available. To handle such cases, System Verilog provides forward declaration of classes using the typedef keyword. This feature allows you to declare a class type without defining its contents, enabling the use of the class handle in declarations, parameters, or method arguments before its full definition is known.
What is Forward Declaration?
A forward declaration allows you to declare a class type without defining its structure or members. This is useful when:
- Two or more classes reference each other, creating a cyclic dependency.
- A class needs to reference another class that will be defined later in the code.
By forward-declaring a class, you inform the compiler about the existence of the class type, even though its complete details are not yet available.
Syntax
typedef class ClassName;
Example 1:
typedef class Packet; // Forward declaration
class Processor;
Packet pkt; // Use Packet class handle
endclass
class Packet; // Full definition of Packet class
int id;
string data;
function void display();
$display("Packet ID: %0d, Data: %s", id, data);
endfunction
endclass
module tb;
Processor proc;
initial begin
proc = new();
proc.pkt = new();
proc.pkt.id = 100;
proc.pkt.data = "Forward Declaration Example";
proc.pkt.display();
end
endmodule
Explanation
- The
Packetclass is forward-declared usingtypedef class Packet;. - The
Processorclass declares a handle toPacketbefore its full definition is available. - Later in the code, the
Packetclass is fully defined.
Output
Packet ID: 100, Data: Forward Declaration Example
Example 2:
A parameterized class references another class that is defined later.
typedef class Payload; // Forward declaration
class Packet #(type T = Payload); // Parameterized class
T payload_data;
function void display();
$display("Packet contains payload data");
endfunction
endclass
class Payload; // Full definition of Payload class
int size;
string content;
function void display();
$display("Payload Size: %0d, Content: %s", size, content);
endfunction
endclass
module tb;
Packet #(Payload) pkt;
initial begin
pkt = new();
pkt.payload_data = new();
pkt.payload_data.size = 128;
pkt.payload_data.content = "Sample Payload";
pkt.display();
pkt.payload_data.display();
end
endmodule
Explanation
Payloadis forward-declared to allow its use as a parameter in thePacketclass.- The
Packetclass usesPayloadas the default type for its parameterized field. - The full definition of
Payloadis provided later in the code.
Output
Packet contains payload data
Payload Size: 128, Content: Sample Payload