Solidity Inheritance – How to Call a Function in Parent Contract from Child Contract?

remixsoliditysolidity-0.6.x

I am new to solidity.. please bear with my foolish question

I would like to get the variable called num in a parent contract from its children.

So, what I have in my mind is to try to get the address of parent contract first, then
I will produce the instance to gain the num in the parent contract.

pragma solidity ^0.6.0;

contract parent{  
    uint public num;  
    function setValue(uint _value) public{  
        num= _value;  
    }  
    function getValue() public view returns(uint){  
        return num;  
    }  
}  
contract child is parent{    
    function get_address() public view returns(address){  
        return address(parent);  // here I have got an error... 
    }  
}  

would you guys give me some advice ?

Best Answer

I got confused in the explanation, but I believe what you're trying to achieve is reading and updating the state of the parent contract from child contract. Here is how you can achieve it:

pragma solidity ^0.6.0;

contract parent {  
    uint public num;
    
    function setValue(uint _value) public {  
        num = _value;  
    }
    
    function getValue() public view returns(uint) {  
        return num;  
    }  
}


contract child {
    parent parentInstance;
    constructor(address _parent_address) public {
        parentInstance = parent(_parent_address);
    }
    
    function getParentValue() public view returns(uint){  
        return parentInstance.getValue();
    }  
    
    function setParentValue(uint _child_value) public {
        parentInstance.setValue(_child_value);
    }  
}

The difference in my example is that in the child contract I've created instance of the parent contract and now you can refer to parents contract state. This is achieve by passing the address of the parent contract inside the constructor of child contract.

Additional logic, how to pass the address automatically to child contract:

pragma solidity ^0.6.0;

contract parent {
    child public childContract;
    uint public num;
    
    constructor() public {
        childContract = new child(address(this));
    }
    
    function setValue(uint _value) public {  
        num = _value;  
    }
    
    function getValue() public view returns(uint) {  
        return num;  
    }  
}


contract child {
    parent parentInstance;
    constructor(address _parent_address) public {
        parentInstance = parent(_parent_address);
    }
    
    function getParentValue() public view returns(uint){  
        return parentInstance.getValue();
    }  
    
    function setParentValue(uint _child_value) public {
        parentInstance.setValue(_child_value);
    }  
}
Related Topic