Solidity Inheritance Constructors
An inheritance constructor passes values from a child to its parents when the child is created. The child names each parent and its arguments in its own constructor.
A child passes a fixed value to its parent
Item is created with Priced(5). Its price reads back as 5.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Priced {
uint256 public price;
constructor(uint256 newPrice) {
price = newPrice;
}
}
contract Item is Priced {
constructor() Priced(5) {
}
}Parent constructors run base-first, in list order
First builds, then Second, then the child. The log shows that order.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract First {
event FirstBuilt();
constructor() {
emit FirstBuilt();
}
}
contract Second {
event SecondBuilt();
constructor() {
emit SecondBuilt();
}
}
contract Ordered is First, Second {
event ChildBuilt();
constructor() {
emit ChildBuilt();
}
}A child passes its own argument onward
Scaled takes 4 and doubles it for Priced. Its price reads back as 8.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Priced {
uint256 public price;
constructor(uint256 newPrice) {
price = newPrice;
}
}
contract Scaled is Priced {
constructor(uint256 x) Priced(x * 2) {
}
}Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Named {
string public name;
constructor(string memory newName) {
name = newName;
}
}
contract Priced {
uint256 public price;
constructor(uint256 newPrice) {
price = newPrice;
}
}
contract Product is Named, Priced {
uint256 public stock;
constructor(string memory newName, uint256 newPrice, uint256 newStock)
Named(newName)
Priced(newPrice)
{
stock = newStock;
}
}Key points
- Parent arguments: A child passes arguments as constructor() Base(5) { }.
- Own arguments: A child can take its own parameters and pass them on, as in Base(arg).
- Base first: Parent constructors run before the child's own constructor body.
- List order: Parents run most-base-like first, in the order of the inheritance list.
In this example, Named takes a name and Priced takes a price. Product inherits from both and takes a third value, stock, of its own. Its constructor passes the name to Named and the price to Priced, then sets stock in its own body.
Note
A parent without a constructor needs no arguments from the child.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
When a child with two parents is created, in what order do the constructors run?