Home > Mobile >  Solidity inheritance override public constant
Solidity inheritance override public constant

Time:11-12

Simple code:

pragma solidity 0.8.4;

contract A {
    uint256 public constant X = 1;
}

contract B is A {
    uint256 override public constant X = 2;
}

Unfortunately that errors on compile:

TypeError: Cannot override public state variable.
 --> contracts/mocks/StakePoolMock.sol:4:5:
  |
4 |     uint256 public constant X = 1;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note: Overriding public state variable is here:
 --> contracts/mocks/StakePoolMock.sol:8:5:
  |
8 |     uint256 override public constant X = 2;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Is there any way to override public constants?

CodePudding user response:

The value of the constant variable is assigned during the compiling process then stored in the memory. Unfortunately you can't alter it.

I don't know the purpose of X in your code, but simple state variables can be reassigned easily and by using the onlyOwner modifier you will have exclusive access to the function so you can change the variable anytime.

function changeValue(uint256 newValue) public onlyOwner {
    X = newValue;
}
  • Related