Solidity Inheritance: Virtual & Override Keywords Explained

Added:

Composition over Inheritance in Smart Contract Design

While Solidity's virtual and override keywords facilitate classical object-oriented inheritance, many security auditors and smart contract architects advocate for "Composition over Inheritance." Deep inheritance hierarchies in smart contracts introduce significant security risks, such as state variable shadowing, unexpected execution paths, and obscured code readability—making audits highly challenging. Furthermore, extensive inheritance can lead to bloated bytecode, risking breach of the Ethereum virtual machine's 24KB contract size limit (EIP-170). Instead of overriding functions in child contracts, critics recommend using modular library contracts, external calls, and design patterns like the Diamond Standard (ERC-2535) or proxy patterns. These alternative approaches promote cleaner separation of concerns, easier upgrades, and more predictable security profiles.

Basic understanding of Object-Oriented Programming (OOP) principles, specifically the concept of class inheritance.
Familiarity with basic Solidity syntax, including contract definition, state variables, and functions.
Understanding how basic contract inheritance is declared in Solidity using the 'is' keyword.
Knowledge of Solidity function visibility specifiers (public, external, internal, and private) and how they restrict access.
How to define and implement Abstract Contracts and Interfaces in Solidity, where functions are implicitly virtual.
Understanding Multiple Inheritance in Solidity and how the compiler resolves function calls using C3 Linearization.
Utilizing the 'super' keyword to call parent contract functions within overridden methods.
Advanced smart contract design patterns (such as Upgradeable Proxies and the Factory Pattern) that rely heavily on polymorphism.
16K views302likes3:59@smartcontractprogrammerOriginal Release: 2021-11-25

In Solidity, inheritance allows child contracts to reuse parent contract code while customizing specific functions. To enable function customization, parent contracts must declare functions as 'virtual', and child contracts must use the 'override' keyword when redefining those functions. Functions not overridden in the child contract remain accessible from the parent, enabling multiple levels of inheritance where each level can override functions from its parent.