Inheritance
Learn about inheritance in Solidity.
We'll cover the following...
One of the key components of an object-oriented programming language is inheritance. It’s a technique for enhancing a program’s functionality that separates the code, lessens dependence, and improves the reusability of the current code.
Inheritance between smart contracts is supported by Solidity, allowing several contracts to be inherited into a single contract. A derived contract inherits features from a base contract, which is the contract from which additional contracts derive their features. They are simply known as parent-child contracts.
In Solidity, only internal and public modifiers are capable of inheritance. Some of Solidity’s major highlights include:
All nonprivate members, including state variables and internal methods, are accessible to derived contracts. However, employing this is restricted.
Function overriding is permitted as long as the function signature is maintained. The compilation will fail if the output parameters are different.
The
super
keyword or the super contract name can invoke a super contract’s function.Function calls made with
super
give precedence to the majority of derived contracts when there are multiple inheritances.
We can use the is
keyword to inherit the contract as follows:
// A is a derived contract of Bcontract A is B{// implementation}
Function overriding
Developers can change how a function from a parent contract works in a derived class. This process is called function overriding.
To make it clear that a function in the parent contract can be overridden in the derived contract, it must be defined with the keyword virtual
. Additionally, the keyword override
must be present in the overriding function. We might want another function to take precedence over the overriding function. This is okay and can be accomplished by continuing to use the virtual
keyword. ...