Virtual and override keywords help control how functions behave when you change or extend code. They let you change parts of a program safely without breaking it.
Virtual and override keywords in Blockchain / Solidity
contract Base {
function example() public virtual {
// base code
}
}
contract Child is Base {
function example() public override {
// new code
}
}virtual means the function can be changed in child contracts.
override means the function is changing a virtual function from a parent contract.
contract Animal {
function sound() public virtual returns (string memory) {
return "Some sound";
}
}contract Dog is Animal { function sound() public override returns (string memory) { return "Bark"; } }
contract Cat is Animal { function sound() public override returns (string memory) { return "Meow"; } }
This program shows a base contract Vehicle with a virtual function move(). Two contracts, Car and Bike, override move() to give their own messages. The Test contract calls both to show the different results.
pragma solidity ^0.8.0; contract Vehicle { function move() public virtual returns (string memory) { return "Vehicle is moving"; } } contract Car is Vehicle { function move() public override returns (string memory) { return "Car is driving"; } } contract Bike is Vehicle { function move() public override returns (string memory) { return "Bike is pedaling"; } } contract Test { function testMove() public pure returns (string memory, string memory) { Car car = new Car(); Bike bike = new Bike(); return (car.move(), bike.move()); } }
Always mark functions as virtual in the base contract if you want child contracts to change them.
When overriding, you must use the override keyword to avoid mistakes.
If you forget virtual or override, the compiler will give an error to help you fix it.
virtual lets a function be changed in child contracts.
override shows a function is changing a virtual function from a parent.
Using these keywords helps keep your blockchain contracts safe and easy to update.