DEV Community

Yao Marius SODOKIN
Yao Marius SODOKIN

Posted on

Shadowing Inherited State Variables

Inheritance is a fundamental concept in object-oriented programming, allowing developers to create new classes that inherit properties and methods from existing ones. However, when it comes to state variables, there is a potential pitfall that developers should be aware of: shadowing inherited state variables.

Shadowing occurs when a subclass defines a state variable with the same name as one in its superclass, effectively hiding the inherited variable. This can lead to unexpected behavior and can make the code harder to understand and maintain.

A practical example of shadowing inherited state variables can be seen in the following Solidity code:

pragma solidity ^0.8.17;

contract Parent {
    uint256 public x;

    function setX(uint256 _x) public {
        x = _x;
    }
}

contract Child is Parent {
    uint256 public x;

    function setX(uint256 _x) public {
        x = _x;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, both the Parent and Child contracts have a state variable named x. The Child contract inherits from the Parent contract and has its own declaration of x, which is called "shadowing".

When the Child contract's setX function is called, it updates its own x state variable and not the inherited x from the Parent contract. This is because the state variable in the Child contract shadows the inherited state variable from the Parent contract.

In other words, the Child contract has a new storage location for the x state variable, separate from the one in the Parent contract. The Child contract's state variable takes precedence over the inherited state variable from the Parent contract.

In conclusion, shadowing inherited state variables can lead to unexpected behavior and can make the code harder to understand and maintain. To avoid shadowing, developers should consider using a different name, using the "super" keyword, or using composition instead of inheritance. Additionally, developers should also consider the security implications of inherited state variables to ensure that sensitive information is protected.

Top comments (0)