Inheritance And Modifiers

Inheritance

There are two types of inheritance:

  1. Single
  2. Multi-level

Single inheritance inherits functions, modifiers, events, and variables from the parent class.

Whereas multi-level inheritance creates multiple parent child relationships. Contract A is a parent of contract B and contract B is a parent of contract C.

Example of Inheritance

Import “./owned.sol”;
    Contract InheritanceExample is owned{
    …..
}

The “is” keyword is used for inheritance in solidity.

Example of Single Inheritance

pragma solidity > 0.8 .0 <= 0.9 .0;
contract Inheritance_A {
    function car_1() public pure virtual returns(string memory) {
        return "Inheritance_A";
    }

    function car_2() public pure virtual returns(string memory) {
        return "Inheritance_A";
    }

    function car_3() public pure virtual returns(string memory) {
        return "Inheritance_A";
    }
}
contract Inheritance_B is Inheritance_A {
    function car_1() public pure override returns(string memory) {
        return "Inheritance_B";
    }

    function car_2() public pure override returns(string memory) {
        return "Inheritance_B";
    }
}

When this is deployed,

Inheritance_B is deployed and we can see that in Inheritance_B there is no car_3, but we can see a function while it is deployed.

Example of multi-level Inheritance

contract Inheritance_C is Inheritance_A,Inheritance_B{
    function car_1() public pure override(Inheritance_A,Inheritance_B) returns (string memory){
    return "Inheritance_C";
}
function car_2() public pure override(Inheritance_A,Inheritance_B) returns (string memory){
    return "Inheritance_C";
}

Advantages of Inheritance

  • It has the ability to modify a contract and reflect the modifications in another contract.
  • Inheritance is mainly used to reuse the existing code.
  • Reduce the dependency.

Modifiers

  • Modifiers are used to change the behavior of the function.
  • It automatically checks pre-conditions.

Example of Modifier

Modifier only owner{
    require (msg.sender== owner, “you are not the owner”);
   }
_;
}

­­The symbol _; is called a merge wildcard. It is used to merge the function code with the modifier code.