🎓 A1Learner
🔍
0 of 50 lessons completed

Solidity Constructors

A constructor is a special function that runs once when a contract is created. It sets the starting values the contract begins with.

A constructor sets a starting value

The constructor runs at creation. It can set a state variable before any other function is called.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract ScoreBoard {
    uint256 public score;

    constructor() {
        score = 10;
    }
}

A constructor can take an argument

A constructor can take a parameter like a function. The value in the deploy call becomes the starting value.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract StartingScore {
    uint256 public score;

    constructor(uint256 startingScore) {
        score = startingScore;
    }
}

A constructor can record two starting values

One constructor can set several state variables. Each argument fills one starting value.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract GameSetup {
    uint256 public players;
    uint256 public rounds;

    constructor(uint256 startingPlayers, uint256 startingRounds) {
        players = startingPlayers;
        rounds = startingRounds;
    }
}

Example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract Adventure {
    uint256 public level;
    uint256 public coins;
    uint256 public lives;

    constructor(uint256 startingCoins) {
        level = 1;
        coins = startingCoins;
        lives = 3;
    }
}

Key points

  • Constructor: a special function that runs once, when the contract is created.
  • Deploy: to put a contract on the blockchain, the shared record many computers keep.
  • No name: a constructor uses the word constructor instead of a function name.
  • Arguments: a constructor can take parameters, and the creator supplies their values at deploy time.
  • No second run: a constructor cannot be called again after the contract is created.
  • Starting state: values set in a constructor become the values the contract starts with.

In this example, the Adventure contract has three state variables. Its constructor takes startingCoins as an argument. It sets level to 1 and lives to 3 by itself. It stores the argument in coins, so a deploy with 250 starts the contract with 250 coins.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

When does a constructor run?