I found a strange error in my contract and tried to resolve it, but it's so unreasonable.

contract parentContract {

    uint num = 1;

    function setNum(uint _n) public returns(uint) {
        num = _n;
        return num;
    function getNum() public view returns(uint) {
        return num;

import "./parentContract.sol"

contract childContract is parentContract {
    /* Same name but IDE don't report error
    *function getNum() public view returns(uint) {
    *    return num;

    function getNum2() public view returns(uint) {
        return num;
    function getNum3() public view returns(uint) {
        return getNum();
    function getNum4() public view returns(uint) {
        return parentContract.getNum();

They are simple contracts in two .sol files for testing. I hope the getNum2() will return the num in parentContract, but it always return 1 that I set first. Both getNum3()/getNum4() get the same result with getNum2().

I used truffle V4.1.14 for deploying. Here are my code interacted with contract, in the Command Terminal.

parentContract.deployed().then(function(instance){return instance.setNum(2);});**//Set the num**
parentContract.deployed().then(function(instance){return instance.getNum();}).then(function(value){ return value.toNumber();});**//Get num in parentContract**
childContract.deployed().then(function(instance){return instance.getNum2();}).then(function(value){ return value.toNumber();});**//Get num through child**
childContract.deployed().then(function(instance){return instance.getNum2.call();}).then(function(value){ return value.toNumber();});**//Another method, use call() for testing, same with above.**`
  • Have your run setNum of parentContract? – Aniket Dec 3 '18 at 7:04
  • Of course, I also tried getNum() of parent and it worked well. – user48469 Dec 3 '18 at 7:19
  • On Remix, contract is working fine. It is returning updated values. – Aniket Dec 3 '18 at 7:45
  • Please share your test code. – goodvibration Dec 3 '18 at 9:02
  • I'm not sure, you mean the code interacted with contract ( of truffle) ? I add them above now. – user48469 Dec 3 '18 at 9:49

parentContract.deployed() and childContract.deployed() are two different instances.

You are calling instance.setNum(2) only for the first instance.

So the value of num in the second instance remains 1.

And instance.getNum2() returns that value.

| improve this answer | |
  • I got it! So for inheritance I just need to interact with the final-child contract, all parents codes will be copied, I know what that means now. Thank you so much! – user48469 Dec 3 '18 at 10:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.