Skip to main content
Solidity is an object-oriented language. Contracts can inherit from one another, allowing efficient reuse of code.

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 called Inheritance.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 the is keyword in the contract declaration. Update ContractA so that it is ContractB, and delete the whoAmI function from ContractA.
Deploy and test again. Even though 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 the internal 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.
Deploy and test. Note that in the deployment for 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 a private function from a contract that inherits from the contract containing that function.
The compiler will raise an error:

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 the artifacts folder. Any empty contract:
Will compile into something similar to this:
A slightly more complex contract:
Will have more complex bytecode. In this case, mostly to store the long string present in the return:
However, if the empty contract inherits from the not empty contract:
The resulting bytecode will include that of the contract inherited from:

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 call internal 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.