Programming Language/Solidity

Solidity - Shadowing Inherited State Variables

Yongari 2022. 12. 31. 22:36

 

 

Shadowing Inherited State Variables
상속된 상태 변수 섀도잉

Unlike functions, state variables cannot be overridden by re-declaring it in the child contract.
기능과 달리 상태 변수는 자식 계약에서 다시 선언하여 무시할 수 없습니다.

Let's learn how to correctly override inherited state variables.
상속된 상태 변수를 올바르게 재정의하는 방법에 대해 알아보겠습니다.

 

 

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract A {
    string public name = "Contract A";

    function getName() public view returns (string memory) {
        return name;
    }
}

// Shadowing is disallowed in Solidity 0.6
// This will not compile
// Solidity 0.6에서는 섀도잉이 허용되지 않습니다.
// 이것은 컴파일되지 않습니다.

// contract B is A {
//     string public name = "Contract B";
// }

contract C is A {
    // This is the correct way to override inherited state variables.
    constructor() {
        name = "Contract C";
    }

    // C.getName returns "Contract C"
}

 

Try on Remix

 

Remix - Ethereum IDE

 

remix.ethereum.org