Solidity 솔리디티 강좌 12강 : 두 개 이상 상속하기

flowing1ife·2023년 7월 7일
0

[ Solidity 깨부수기 ]

목록 보기
12/29
post-thumbnail

Solidity 솔리디티 강좌 12강 : 두개 이상 상속하기
이번엔 solidity에서 두 개 이상 상속하는 방법에 대해 알아보도록 하자.


두 개 이상 상속하기

📌 Solidity

// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;

contract Father{
    uint256 public fatherMoney = 100;
    function getFatherName() public pure returns(string memory){
        return "KimJung";
    }

    function getMoney() public view returns(uint256){
        return fatherMoney;
    }
}

contract Mother{
    uint256 public motherMoney = 500;
    function getMotherName() public pure returns(string memory){
        return "Leesol";
    }

    function getMoney() public view returns(uint256){
        return motherMoney;
    }
}

contract Son is Father, Mother{
    
}

코드를 위와 같이 작성하였을 때, 에러가 발생한다. getMoney 함수가 상속받은 컨트랙트 Father, Mother 에 모두 존재하기 때문이다. 따라서 이 때에는 필수적으로 오버라이딩을 해야한다.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;

contract Father{
    uint256 public fatherMoney = 100;
    function getFatherName() public pure returns(string memory){
        return "KimJung";
    }

    function getMoney() public view virtual returns(uint256){
        return fatherMoney;
    }
}

contract Mother{
    uint256 public motherMoney = 500;
    function getMotherName() public pure returns(string memory){
        return "Leesol";
    }

    function getMoney() public view virtual returns(uint256){
        return motherMoney;
    }
}

contract Son is Father, Mother{
   //추가
    function getMoney() public view override(Father, Mother) returns(uint256){
        return fatherMoney + motherMoney;
    }
}

Son 컨트랙트에서 fatherMoney + motherMoney를 return 하도록 getMoney 함수를 오버라이딩 하였다.

위와 같이 오버라이딩이 되는 함수에는 virtual을 붙여주고, 오버라이딩을 하는 함수는 override(상속받는 컨트랙트들)를 붙여주었다.

👉 결과

Son 컨트랙트를 배포 후, getMoney 함수를 호출하면 100 + 500 의 값인 600이 return되는 것을 알 수 있다.


출처 및 참고 자료

profile
👩🏻‍💻 Backend Engineer, Contract Developer

0개의 댓글