Inheritance of another intelligent contract: Understanding storage in Ethereum

Ethereum: Working with storage when inheriting from another smart contract

When writing smart contracts, the Ethereum blockchain is one of the basic concepts that need to be seized is inheritance. Inheritance allows a new contract (the heir) to build or modify the functionality of the existing contract (parent). However, there is a decisive aspect that needs to be taken into account when working with storage: “This” is a keyword and its consequences.

In your example, the contract has a “unchanged” variable, “X”, initialized in value 42. In a contract B, which inherits from the contract, it is not explicitly determined that “Y” inheritance must be left or has a given value. However, we examine why it seems that “Y” is set to 0 in the B contract.

Why does not inherit y y from that contract?

In Ethereum contracts, when the “unrealistic” keyword is used, inheritance does not affect non-unplugged variables (like the constants). The reason for this is that the immutability is a contractual level that prevents change after calling the constructor.

You can see that you set the B contract to “Y” 0, thanks to the storage of Ethereum for the inherited variables:

1

2.

  • Since “Y” is not explicitly initialized in the call of contract B, by default, 0.

Solution: Assign value to “Y”

You have some options to solve the problem:

1.

`Solidity

Contract with {

Uint indispensable x;

constructor () {

x = 42;

y = 0; // Assigning a value specifically to y

}

...

}

  • Use the “memory” storage type : If you work with intelligent contracts, it is often more convenient to use the “memory” storage type instead of “storage”. The “memory” type allows dynamic distribution and arrangement of memory as needed.

`Solidity

Contract with {

Uint indispensable x;

constructor () public {

x = 42;

}

...

}

A contract B extends the {

Function sety (uint y) public {

// y already available in contract B

}

}

In this example, “Y” can be modified directly without affecting the inheritance.

Leave a Reply

Your email address will not be published. Required fields are marked *