Home > Software engineering >  Is it possible to inherit the Ethereum contract to my contract?
Is it possible to inherit the Ethereum contract to my contract?

Time:11-01

Is it possible to inherit the Ethereum contract it self and add some function to it?

I just want to know it is possible to do and if it is how?

CodePudding user response:

Is it possible to inherit the Ethereum contract it self and add some function to it?

No, because it does not make sense.

Please check out this tutorial on how to ask questions, reword your question and give context on your real problem.

CodePudding user response:

Inheritance is one of the most important features of the object-oriented programming language, Solidity supports inheritance between smart contracts,

There is a base contract which is the main class that contains code that can be passed on to other contracts. This is also called the parent contract. The other contracts are derived from the base, and are called child contracts. The child inherits from the parent, and a parent can have multiple children.

The parent contains functions, with methods and routines that a child can inherit and use. When a contract inherits from another contract, it is referred to as single inheritance. It is also possible, as in many cases, for a child to inherit from multiple parents and this is called multiple inheritance.

Here is a sample code of single inheritance using Contract A and Contract B

// Single Inheritance

pragma solidity ^0.8.7;
contract A {
    function foo() public pure virtual returns (string memory) {
           return "Foo Contract A";
    }

    function bar() public pure returns (string memory) {
          return "Bar Contract A";
    }
contract B is A {
    function foo() public pure override returns (string memory) {
         return "Foo Contract B";
    }
}

Contract B is inheriting from Contract A. In order to allow inheritance, the is keyword is added to the contract statement. That means:

contract B is A {}

In the child contract B, we have a function that is also called foo(). What if we want to bypass the value from A? You have to use the override keyword.

For this to work, you have to declare the function in A that B will inherit with the keyword virtual. That allows B to set its own value for foo(), that is not the same as A. B can return the value “Foo Contract B” instead of “Foo Contract A”.

  • Related