Objectives
By the end of this lesson you should be able to:- Write a smart contract that inherits from multiple contracts
Multiple Inheritance
Continue working with your contracts inInheritance.sol
. Add a new contract called ContractC
with another whoAmI
function:
Reveal code
Reveal code
Inheriting from Two Contracts
You can inherit from additional contracts by simply adding a comma and that contract’s name after the first. Add inheritance fromContractC
(an error is expected):
Reveal code
Reveal code
ContractB
and ContractC
contain a function called whoAmI
. As a result, the compiler needs instruction on which to use.
Using Virtual and Override
One method to resolve this conflict is to use thevirtual
and override
keywords to enable you to add functionality to choose which to call.
Add the virtual
keyword to the whoAmI
function in both ContractC
and ContractB
.
They must also be made public
instead of external
, because external
functions cannot be called within the contract.
override
function called whoAmI
to ContractA
:
Changing Types Dynamically
Add anenum
at the contract level in ContractA
with members for None
, ContractBType
, and ContractCType
, and an instance of it called contractType
.
Reveal code
Reveal code
constructor
to ContractA
that accepts a Type
and sets initialType
.
Reveal code
Reveal code
whoAmI
in ContractA
to call the appropriate virtual
function based on its currentType
.
Reveal code
Reveal code
pure
. Update it to view
. You’ll also have to update the whoAmI
virtual
functions to view
to match.
Reveal code
Reveal code
currentType
:
Reveal code
Reveal code
contractType
, because Remix won’t know about your enum
.