What is Constructor in Solidity: Definition and Usage
constructor is a special function that runs only once when a smart contract is created. It is used to initialize the contract's state or set up important variables before the contract starts working.How It Works
Think of a constructor like the setup instructions you give when you buy a new gadget. Before you start using it, you need to configure some settings. Similarly, in Solidity, the constructor runs only once when the contract is deployed to the blockchain. It sets initial values or prepares the contract for use.
This function has no name but is declared with the keyword constructor. After the constructor finishes, it never runs again. This ensures the contract starts with the right setup, like setting an owner or initial balance.
Example
This example shows a contract with a constructor that sets the owner when the contract is created.
pragma solidity ^0.8.0; contract SimpleContract { address public owner; constructor() { owner = msg.sender; // Set the deployer as the owner } function getOwner() public view returns (address) { return owner; } }
When to Use
Use a constructor whenever you need to set up your contract with initial information that should not change later. For example, you might set the contract owner, initialize token supply, or configure important settings.
This is useful in real-world cases like creating a token contract where the total supply is fixed at deployment or setting an admin who can manage the contract.
Key Points
- The constructor runs only once when the contract is deployed.
- It is declared with the
constructorkeyword and has no return type. - It is used to initialize contract state variables.
- After deployment, the constructor cannot be called again.