Objectives
By the end of this lesson you should be able to:- Write a smart contract that inherits from another contract
- Describe the impact inheritance has on the byte code size limit
Inheritance
Create a new contract file in Remix calledInheritance.sol
and add two simple contracts, each with a function identifying which contract called it:
ContractA
says that it is “contract A” and ContractB
says that it is “contract B”.
Inheriting from Another Contract
Inheritance between contracts is indicated by theis
keyword in the contract declaration. Update ContractA
so that it is
ContractB
, and delete the whoAmI
function from ContractA
.
Reveal code
Reveal code
ContractA
doesn’t have any functions in it, the deployment still shows the button to call whoAmI
. Call it. ContractA
now reports that it is “contract B”, due to the inheritance of the function from Contract B
.
Internal Functions and Inheritance
Contracts can call theinternal
functions from contracts they inherit from. Add an internal
function to ContractB
called whoAmIInternal
that returns “contract B”.
Add an external function called whoAmIExternal
that returns the results of a call to whoAmIInternal
.
Reveal code
Reveal code
ContractB
, the whoAmIInternal
function is not available, as it is internal
. However, calling whoAmIExternal
can call the internal
function and return the expected result of “contract B”.
Internal vs. Private
You cannot call aprivate
function from a contract that inherits from the contract containing that function.
Inheritance and Contract Size
A contract that inherits from another contract will have that contract’s bytecode included within its own. You can view this by opening settings in Remix and turning Artifact Generation back on. The bytecode for each compiled contract will be present in the JSON file matching that contract’s name within theartifacts
folder.
Any empty contract:
Conclusion
In this lesson, you’ve learned how to use inheritance to include the functionality of one contract in another. You’ve also learned that inheriting contracts can callinternal
functions, but they cannot call private
functions. You’ve also learned that inheriting from a contract adds the size of that contract’s bytecode to the total deployed size.