Looking through an OpenZeppelin tutorial, I came across this code snippet:
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract GameItem {
constructor() ERC721("GameItem", "ITM") {}
What is the syntax in the constructor that allows a class instance to be passed in after constructor()? I can’t seem to find any reference to this in the Solidity docs
It's invoking a parent constructor, in this case the parent class is named ERC721
. It's the same as calling super.constructor()
or parent.constructor()
in some other languages.
In order to call the parent constructor, your contract needs to actually inherit from it:
contract GameItem is ERC721 {
Solidity supports inheritance from multiple parents. That's why you cannot just use an ambiguous keyword such as parent
. By explicitly stating the parent class name, you can specify which values you want to pass to which parent:
pragma solidity ^0.8;
contract Parent1 {
constructor(string memory message1) {}
}
contract Parent2 {
constructor(string memory message2) {}
}
contract Child is Parent1, Parent2 {
constructor() Parent1("hello") Parent2("world") {}
}
Docs: https://docs.soliditylang.org/en/v0.8.13/contracts.html#arguments-for-base-constructors