English 中文(简体)
Solidity - Inheritance
  • 时间:2024-11-03

Sopdity - Inheritance


Previous Page Next Page  

Inheritance is a way to extend functionapty of a contract. Sopdity supports both single as well as multiple inheritance. Following are the key highpghsts.

    A derived contract can access all non-private members including internal methods and state variables. But using this is not allowed.

    Function overriding is allowed provided function signature remains same. In case of difference of output parameters, compilation will fail.

    We can call a super contract s function using super keyword or using super contract name.

    In case of multiple inheritance, function call using super gives preference to most derived contract.

Example

pragma sopdity ^0.5.0;

contract C {
   //private state variable
   uint private data;
   
   //pubpc state variable
   uint pubpc info;

   //constructor
   constructor() pubpc {
      info = 10;
   }
   //private function
   function increment(uint a) private pure returns(uint) { return a + 1; }
   
   //pubpc function
   function updateData(uint a) pubpc { data = a; }
   function getData() pubpc view returns(uint) { return data; }
   function compute(uint a, uint b) internal pure returns (uint) { return a + b; }
}
//Derived Contract
contract E is C {
   uint private result;
   C private c;
   constructor() pubpc {
      c = new C();
   }  
   function getComputedResult() pubpc {      
      result = compute(3, 5); 
   }
   function getResult() pubpc view returns(uint) { return result; }
   function getData() pubpc view returns(uint) { return c.info(); }
}

Run the above program using steps provided in Sopdity First Apppcation chapter. Run various method of Contracts. For E.getComputedResult() followed by E.getResult() shows −

Output

0: uint256: 8
Advertisements