0
0
Blockchain / Solidityprogramming~5 mins

Constructor function in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

A constructor function sets up a new smart contract with initial values when it is created. It helps prepare the contract to work correctly from the start.

When you want to set the owner of a smart contract right away.
When you need to give initial values like token name or supply.
When you want to set important settings that should not change later.
When you want to make sure some data is ready before anyone uses the contract.
Syntax
Blockchain / Solidity
constructor() {
    // code to run once when contract is created
}
The constructor runs only once, when the contract is deployed.
You can pass parameters to the constructor to set initial values.
Examples
This constructor sets the owner to the address that creates the contract.
Blockchain / Solidity
contract MyContract {
    address public owner;

    constructor() {
        owner = msg.sender;
    }
}
This constructor takes a token name and supply when the contract is created.
Blockchain / Solidity
contract Token {
    string public name;
    uint public totalSupply;

    constructor(string memory _name, uint _supply) {
        name = _name;
        totalSupply = _supply;
    }
}
Sample Program

This smart contract sets the owner to the creator and stores an initial balance passed when deployed. It also has a function to check the balance.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract SimpleWallet {
    address public owner;
    uint public balance;

    constructor(uint initialBalance) {
        owner = msg.sender;
        balance = initialBalance;
    }

    function getBalance() public view returns (uint) {
        return balance;
    }
}
OutputSuccess
Important Notes

Constructor functions cannot be called again after deployment.

If you do not write a constructor, a default empty one is used.

Use msg.sender to get the address that creates the contract.

Summary

Constructor functions run once when the contract is created.

They set up initial values and important settings.

They help make your contract ready to use safely.