Inheritance
Learn how to reuse standard code
In the previous section, we foreshadowed inheritance, a concept that Solidity shares with other object-oriented programming languages. In this section, we will go over how to inherit other smart contracts and introduce inheritance in the concept of contract constructors.
B is A
At the most fundamental level, contract inheritance works as follows:
In the code snippet above, we have an arbitrary contract A and a contract B which inherits A. Although simple, this doesn't really explain the full concept of inheritance. Let's consider a more sophisticated example:
In the code above, we have two contract A and B. The definition of contract A is nothing new, but what about contract B? Well, since B is inheriting A, this implies that B has the following properties:
- B has the state variable num
- B has the function square
To really drive home the idea of inheritance, let's consider this final code snippet:
The code snippet above is more sophisticated in that we are explicitly introducing visibility in the context of inheritance. Again, the definition of A should be trivial. Focusing on B, we have the following:
- B does not have the state variable num1 and the function getOne, since these are marked as private and therefore, belong only to A
- B has the state variable name since it is marked as internal and therefore, able to be derived by B
- B has the function getTwo since it is marked as public
Constructors and Inheritance
Just like we can inherit functions from parent functions, we can also inherit constructors from parent contracts. The syntax for inheriting parent functions is as follows:
An example of constructor inheritance can be found below:
For contract A, we are setting num1 equal to 5 at the time of initialization. For contract B, we first call the constructor of A (which sets num1 in B to 5) and then sets num2 to 7.