0
0
Blockchain / Solidityprogramming~10 mins

Constructor function in Blockchain / Solidity - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Constructor function
Contract Deployment
Constructor Called Once
Initialize State Variables
Contract Ready for Use
When a contract is deployed, the constructor function runs once to set up initial values before the contract can be used.
Execution Sample
Blockchain / Solidity
contract Simple {
  uint public x;
  constructor(uint _x) {
    x = _x;
  }
}
This contract sets the variable x to the value given when the contract is created.
Execution Table
StepActionInputState ChangeOutput
1Deploy contract_x = 10x is uninitializedNo output
2Constructor runs_x = 10x set to 10No output
3Contract ready-x = 10No output
💡 Constructor runs once during deployment, then contract is ready with x = 10
Variable Tracker
VariableStartAfter Step 2Final
xuninitialized1010
Key Moments - 2 Insights
Why does the constructor run only once?
The constructor runs only during contract deployment to set initial values. After that, it does not run again, as shown in execution_table step 2.
What happens if you try to call the constructor after deployment?
You cannot call the constructor again after deployment. It is a special function that runs only once, so no state change happens after step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x after step 2?
A10
B0
Cuninitialized
Dundefined
💡 Hint
Check the 'State Change' column in step 2 where x is set to 10.
At which step does the constructor function run?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Action' column to see when the constructor runs.
If the input _x was 20 instead of 10, what would be the final value of x?
A10
B0
C20
Duninitialized
💡 Hint
The constructor sets x to the input value, see variable_tracker for how x changes.
Concept Snapshot
Constructor function:
- Runs once when contract is deployed
- Initializes state variables
- Cannot be called again
- Sets starting values for contract
- Example: constructor(uint _x) { x = _x; }
Full Transcript
A constructor function in blockchain smart contracts runs only once during deployment. It sets initial values for variables so the contract starts with the right data. For example, if a contract has a variable x, the constructor can set x to a value given when deploying. After deployment, the constructor cannot be called again. This ensures the contract's starting state is fixed. The execution table shows deployment, constructor running, and contract ready with x set. The variable tracker shows how x changes from uninitialized to the input value. This helps beginners see the constructor's role clearly.