Skip to main content
Contracts can inherit from more than one contract. In this lesson, we’ll explore how multiple inheritance works in Solidity.

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 in Inheritance.sol. Add a new contract called ContractC with another whoAmI function:

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 from ContractC (an error is expected):
The error is because both 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 the virtual 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.
Add an override function called whoAmI to ContractA:
You’ll get another error, telling you to specify which contracts this function should override.
Add them both:
Deploy and test. The call will now be back to reporting “contract B”.

Changing Types Dynamically

Add an enum at the contract level in ContractA with members for None, ContractBType, and ContractCType, and an instance of it called contractType.
Add a constructor to ContractA that accepts a Type and sets initialType.
Update whoAmI in ContractA to call the appropriate virtual function based on its currentType.
You’ll get errors because the function now reads from state, so it is no longer pure. Update it to view. You’ll also have to update the whoAmI virtual functions to view to match.
Finally, add a function that allows you to switch currentType:
Deploy and test. You’ll need to use 0, 1, and 2 as values to set contractType, because Remix won’t know about your enum.

Final Code

After completing this exercise, you should have something similar to:

Conclusion

In this lesson, you’ve explored how to use multiple inheritance to import additional functionality into a contract. You’ve also implemented one approach to resolving name conflicts between those contracts.