TransWikia.com

C++ (or generally OOP) inheritance in Solidity

Ethereum Asked by luca590 on February 13, 2021

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.

One Answer

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?

Answered by willjgriff on February 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP