In a simple solidity contract, without inheritance, storage variables get assigned sequentially starting from slot 0.
But in case of inheritance, the inherited variables appear before or afterwards?
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityIn a simple solidity contract, without inheritance, storage variables get assigned sequentially starting from slot 0.
But in case of inheritance, the inherited variables appear before or afterwards?
The assignment is as follows: first to the inherited variables, from the leftmost contract to the rightmost, finishing with the current contract you're in.
In the following example C
inherits from Base
and Base2
, in that order. The slot assignment will start from Base
, following Base2
, and finally C
.
pragma solidity ^0.5;
contract Base {
uint256 basevar = 0;
constructor() public {
basevar = 1;
}
}
contract Base2 {
uint256 basevar2 = 2;
constructor() public {
basevar2 = 1;
}
}
contract C is Base, Base2 {
uint256 cvar = 0;
function getCvar() public view returns(uint256) {
return cvar;
}
function getBasevar () public view returns(uint256) {
return basevar;
}
}
basevar
gets assigned slot 0,
basevar2
gets assigned slot 1,
and cvar
gets assigned slot 2.