Complete the code to declare a virtual function in a smart contract.
contract Base {
function greet() public view [1] returns (string memory) {
return "Hello from Base";
}
}The virtual keyword marks a function that can be overridden in a derived contract.
Complete the code to override the virtual function in the derived contract.
contract Derived is Base {
function greet() public view [1] returns (string memory) {
return "Hello from Derived";
}
}The override keyword is used to replace the behavior of a virtual function in a child contract.
Fix the error in the derived contract by adding the correct keyword to the overridden function.
contract Derived is Base {
function greet() public view [1] returns (string memory) {
return "Hello from Derived";
}
}The overridden function must use the override keyword to compile correctly.
Fill both blanks to declare a virtual function and override it correctly.
contract Base {
function calculate() public view [1] returns (uint) {
return 1;
}
}
contract Derived is Base {
function calculate() public view [2] returns (uint) {
return 2;
}
}The base function uses virtual to allow overriding, and the derived function uses override to replace it.
Fill all three blanks to declare a virtual function, override it, and call the base function inside the override.
contract Base {
function info() public view [3] returns (string memory) {
return "Base info";
}
}
contract Derived is Base {
function info() public view [1] returns (string memory) {
return string(abi.encodePacked(Base.[2](), " and Derived info"));
}
}The derived function uses override to replace the base function, calls the base function by its name info, and the base function is marked virtual.