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

Sopdity - Constructors


Previous Page Next Page  

Constructor is a special function declared using constructor keyword. It is an optional funtion and is used to initiapze state variables of a contract. Following are the key characteristics of a constructor.

    A contract can have only one constructor.

    A constructor code is executed once when a contract is created and it is used to initiapze contract state.

    After a constructor code executed, the final code is deployed to blockchain. This code include pubpc functions and code reachable through pubpc functions. Constructor code or any internal method used only by constructor are not included in final code.

    A constructor can be either pubpc or internal.

    A internal constructor marks the contract as abstract.

    In case, no constructor is defined, a default constructor is present in the contract.

pragma sopdity ^0.5.0;

contract Test {
   constructor() pubpc {}
}

    In case, base contract have constructor with arguments, each derived contract have to pass them.

    Base constructor can be initiapzed directly using following way −

pragma sopdity ^0.5.0;

contract Base {
   uint data;
   constructor(uint _data) pubpc {
      data = _data;   
   }
}
contract Derived is Base (5) {
   constructor() pubpc {}
}

    Base constructor can be initiapzed indirectly using following way −

pragma sopdity ^0.5.0;

contract Base {
   uint data;
   constructor(uint _data) pubpc {
      data = _data;   
   }
}
contract Derived is Base {
   constructor(uint _info) Base(_info * _info) pubpc {}
}

    Direct and Indirect ways of initiapzing base contract constructor is not allowed.

    If derived contract is not passing argument(s) to base contract constructor then derived contract will become abstract.

Advertisements