0

In Solidity, when one does inheritance, the two contracts share state. Some pseudocode,

contract A {
uint myVar = 1
setVar() {myVar = 3}
}

contract B is A {
myVar = 2
} 

If I deploy A, A.myVar = 1. If I deploy B and then call A.setVar(), B.myVar = 3 (and not 2).

So clearly, inherited contracts share state in Solidity.

In C++, inherited classes do not share state. If you want this kind of shared state functionality, you would need to use the "virtual" key word to reference data in memory (independent of classes).

How can I get "C++ inheritance" functionality in Solidity? For example, if I deploy A, then deploy B, B inherits the functionality of A (namely setVar()) but they do not share state, so A.myVar = 1 and B.myVar = 2 after deployment of both contracts. If I called A.setVar(), B.myVar would still be 2.

  • "If I deploy A, A.myVar = 1. If I deploy B and then call A.setVar(), B.myVar = 3 (and not 2)." I don't believe that to be true. Can you share exactly what you did that achieved that result? – smarx Jan 22 '18 at 11:58
0

The answer to this question might help a bit here: Solidity, is it possible to deploy a smart contract that prevents other smart contracts from inheriting from it?

Basically inheritance is a feature of the Solidity language, not of the EVM or the bytecode that is processed by it so you cannot call functions on contract B through a reference to contract A.

Ultimately no two deployed contracts can share the same state. I'm not sure what you could be doing wrong above, but the only way you could get b.myVar() = 3 is by doing b.setVar(3) where b is an instance of the deployed contract B.

What are you using to code and experiment with these contracts? Are you using Truffle or Remix or something else?

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.