- Solidity - Discussion
- Solidity - Useful Resources
- Solidity - Quick Guide
- Solidity - Error Handling
- Solidity - Events
- Solidity - Assembly
- Solidity - Libraries
- Solidity - Interfaces
- Solidity - Abstract Contracts
- Solidity - Constructors
- Solidity - Inheritance
- Solidity - Contracts
- Solidity - Restricted Access
- Solidity - Withdrawal Pattern
- Cryptographic Functions
- Mathematical Functions
- Function Overloading
- Solidity - Fallback Function
- Solidity - Pure Functions
- Solidity - View Functions
- Solidity - Function Modifiers
- Solidity - Functions
- Solidity - Style Guide
- Solidity - Special Variables
- Solidity - Ether Units
- Solidity - Conversions
- Solidity - Mappings
- Solidity - Structs
- Solidity - Enums
- Solidity - Arrays
- Solidity - Strings
- Solidity - Decision Making
- Solidity - Loops
- Solidity - Operators
- Solidity - Variable Scope
- Solidity - Variables
- Solidity - Types
- Solidity - Comments
- Solidity - First Application
- Solidity - Basic Syntax
- Solidity - Environment Setup
- Solidity - Overview
- Solidity - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Sopdity - Constructors
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.