What is inheritance in Solidity?
Overview
Solidity supports smart contract inheritance.
Smart contracts in Solidity programming are groups of code. Many smart contracts can be inherited as one smart contract.
Note: Inheritance can only be performed by public and internal modifiers.
Inheritance is a way to expand the usefulness of a contract. Solidity performs both single as well as multiple inheritance.
Key points
-
A derived contract can get to all non-private internal methods and states.
-
Function superseding is permitted, provided that the given function signature remains the same.
-
In case of distinction of yield parameters, compilation will fail.
-
A super contract’s function can be triggered utilizing the
superkeyword or utilizing the name of the super contract. -
In the case of multiple inheritance, function call utilizing
supergives inclination to the most derived contract.
In the example below, the contract parent is inherited by the contract child to demonstrate single inheritance.
pragma solidity >=0.4.22 <0.6.0;// Defining contractcontract parent{uint internal sum;function setValue() external {uint a = 10;uint b = 20;sum = a + b;}}contract child is parent{function getValue() external view returns(uint) {return sum;}}// Defining calling contractcontract caller {// Creating child contract objectchild cc = new child();// Defining function to call// setValue and getValue functionsfunction testInheritance() public returns (uint) {cc.setValue();return cc.getValue();}}
Explanation
-
Line 4: We define a contract.
-
Line 6: We declare the internal state variable.
-
Line 8–12: We define an external function to set the value of the internal state variable
sum. -
Line 14: We define the
child contract. -
Line 16-19: We define an external function to return the value of the internal state variable
sum. -
Line 23: We define the calling contract
contract caller. -
Line 26: We create the child contract object
child cc = new child();. -
Lines 32–33: We define a function to call
setValue()andgetValue()functions.