0
0
Blockchain / Solidityprogramming~15 mins

Constructor function in Blockchain / Solidity - Deep Dive

Choose your learning style9 modes available
Overview - Constructor function
What is it?
A constructor function is a special function in a blockchain smart contract that runs only once when the contract is created. It sets up the initial state or values for the contract, like setting an owner or starting balance. Think of it as the contract's setup step before it starts working. After this, the constructor cannot be called again.
Why it matters
Without constructor functions, every contract would need manual setup after deployment, which is error-prone and inefficient. Constructors ensure contracts start with the right settings automatically, making blockchain applications safer and more reliable. Without them, contracts could be left in incomplete or insecure states, risking loss of funds or trust.
Where it fits
Before learning constructors, you should understand basic smart contract structure and functions. After mastering constructors, you can learn about contract inheritance, modifiers, and upgradeable contracts which often rely on constructor logic.
Mental Model
Core Idea
A constructor function is the contract’s one-time setup routine that runs exactly once when the contract is created to initialize its starting state.
Think of it like...
It's like setting up a new phone for the first time: you choose language, connect to Wi-Fi, and sign in. This setup happens once, so the phone is ready to use. Similarly, the constructor sets up the contract once before it starts working.
┌─────────────────────────────┐
│   Smart Contract Deployment  │
└──────────────┬──────────────┘
               │
               ▼
   ┌─────────────────────────┐
   │  Constructor Function   │  ← Runs once here
   └────────────┬────────────┘
                │
                ▼
   ┌─────────────────────────┐
   │ Contract Ready to Use   │
   └─────────────────────────┘
Build-Up - 6 Steps
1
FoundationWhat is a Constructor Function
🤔
Concept: Introduces the idea of a constructor as a special function that runs once during contract creation.
In blockchain smart contracts, a constructor is a function with the same name as the contract (in older Solidity versions) or marked with the keyword 'constructor' (in modern Solidity). It runs automatically when the contract is deployed and cannot be called again later. Its job is to set initial values like the owner address or starting balances.
Result
The contract starts with predefined values set by the constructor, ready for use.
Understanding that constructors run only once helps prevent mistakes like trying to reinitialize contracts later, which is impossible.
2
FoundationBasic Syntax of Constructor in Solidity
🤔
Concept: Shows how to write a constructor function in Solidity, the main blockchain language.
In Solidity (version 0.4.22 and later), you write a constructor using the 'constructor' keyword: contract MyContract { address public owner; constructor() { owner = msg.sender; // Set deployer as owner } } Here, 'msg.sender' is the address deploying the contract. This sets the owner once at deployment.
Result
The contract stores the deployer's address as the owner immediately after deployment.
Knowing the constructor syntax is essential to correctly initialize contracts and avoid security risks.
3
IntermediatePassing Arguments to Constructors
🤔Before reading on: Do you think constructor arguments can be changed after deployment? Commit to your answer.
Concept: Explains how constructors can take inputs to customize contract setup at deployment time.
Constructors can accept parameters to set initial values dynamically: contract Token { string public name; uint public totalSupply; constructor(string memory _name, uint _supply) { name = _name; totalSupply = _supply; } } When deploying, you provide the name and supply, which the constructor saves.
Result
The contract starts with the name and supply you specify during deployment.
Understanding constructor arguments allows flexible contract initialization tailored to different needs.
4
IntermediateConstructor Visibility and Restrictions
🤔Before reading on: Can a constructor be called by anyone after deployment? Commit to your answer.
Concept: Covers that constructors have no visibility modifiers and cannot be called after deployment.
Constructors do not have visibility keywords like public or private because they run only once during deployment. After deployment, the constructor code is not callable. Trying to call it later will fail. This protects the contract from being reset or reinitialized.
Result
The contract’s initial setup is protected from being changed after deployment.
Knowing constructor restrictions prevents security mistakes like assuming you can re-run setup code.
5
AdvancedConstructors in Inheritance and Multiple Contracts
🤔Before reading on: Do you think constructors of parent contracts run automatically? Commit to your answer.
Concept: Explains how constructors work with contract inheritance and how to call parent constructors.
When a contract inherits from others, each parent contract may have its own constructor. You must call parent constructors explicitly: contract Parent { uint public x; constructor(uint _x) { x = _x; } } contract Child is Parent { constructor(uint _x) Parent(_x) { // Child constructor } } This ensures all parts initialize properly.
Result
All inherited contracts initialize their state correctly during deployment.
Understanding constructor chaining is key to building complex, reusable contracts safely.
6
ExpertConstructor Bytecode and Gas Cost Implications
🤔Before reading on: Does constructor code remain on-chain after deployment? Commit to your answer.
Concept: Reveals that constructor code runs only during deployment and is not stored on-chain, affecting gas costs.
When deploying a contract, the constructor code runs once and is part of the deployment bytecode. After deployment, the constructor code is discarded and not stored on-chain. This means constructor logic costs gas only once, reducing runtime costs. However, complex constructors increase deployment gas cost, so optimizing constructor code saves money.
Result
Efficient constructors reduce deployment cost and keep runtime code smaller.
Knowing constructor code is temporary helps optimize contract deployment and understand gas usage.
Under the Hood
At deployment, the blockchain runs the constructor code as part of the contract creation transaction. The constructor sets initial storage variables and state. After execution, the constructor code is removed from the deployed contract's bytecode, leaving only the runtime code. This ensures the constructor cannot be called again and keeps the contract's on-chain size minimal.
Why designed this way?
Constructors were designed to provide a secure, one-time setup step that prevents reinitialization attacks. Removing constructor code after deployment saves storage space and gas costs. Early blockchain designs needed a clear way to initialize contracts safely without exposing setup functions to later calls.
┌───────────────────────────────┐
│ Deployment Transaction Starts │
└───────────────┬───────────────┘
                │
                ▼
   ┌─────────────────────────┐
   │ Run Constructor Code     │
   │ (Initialize State)       │
   └────────────┬────────────┘
                │
                ▼
   ┌─────────────────────────┐
   │ Store Runtime Bytecode   │
   │ (Constructor Removed)    │
   └────────────┬────────────┘
                │
                ▼
   ┌─────────────────────────┐
   │ Contract Ready on Chain  │
   └─────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Can you call a constructor function again after deployment? Commit to yes or no.
Common Belief:I can call the constructor anytime to reset the contract state.
Tap to reveal reality
Reality:Constructors run only once during deployment and cannot be called again afterward.
Why it matters:Trying to call a constructor later wastes gas and can cause failed transactions, leading to confusion and potential security risks.
Quick: Does constructor code remain part of the contract bytecode on-chain? Commit to yes or no.
Common Belief:Constructor code stays on-chain and runs every time the contract is called.
Tap to reveal reality
Reality:Constructor code is removed after deployment; only runtime code remains on-chain.
Why it matters:Misunderstanding this leads to wrong assumptions about gas costs and contract size, causing inefficient contract design.
Quick: If a contract inherits multiple contracts, do all constructors run automatically without explicit calls? Commit to yes or no.
Common Belief:All parent constructors run automatically without needing to call them explicitly.
Tap to reveal reality
Reality:Parent constructors must be called explicitly in the child constructor to run properly.
Why it matters:Missing explicit calls can leave parts of the contract uninitialized, causing bugs or security flaws.
Quick: Can constructor arguments be changed after deployment? Commit to yes or no.
Common Belief:I can change constructor arguments anytime after deployment by calling the constructor again.
Tap to reveal reality
Reality:Constructor arguments are fixed at deployment and cannot be changed later.
Why it matters:Assuming arguments can change leads to insecure contracts and failed attempts to update critical settings.
Expert Zone
1
Constructors can be used to set immutable variables, which save gas by storing data directly in bytecode rather than storage.
2
In upgradeable proxy patterns, constructors are replaced by initializer functions because constructors run only once and proxies need reinitialization logic.
3
Complex constructor logic increases deployment gas cost significantly, so splitting setup into external initialization functions can optimize costs.
When NOT to use
Avoid using constructors in upgradeable contracts because the proxy pattern requires initializer functions instead. Also, if contract setup needs to be delayed or repeated, use external initialization functions with access control.
Production Patterns
In production, constructors are used to set ownership, initial token supply, and critical configuration. For upgradeable contracts, constructors are minimal or empty, with initialization done via external functions. Constructor arguments are often used to customize deployments for different environments.
Connections
Object-Oriented Programming Constructors
Similar pattern of one-time object initialization
Understanding constructors in OOP helps grasp blockchain constructors as both set initial state once when creating an instance or contract.
Immutable Data Structures
Constructors set immutable initial state that cannot be changed later
Knowing immutable data concepts clarifies why constructor-set values remain fixed, enhancing contract security.
Project Management Initialization Phase
Both involve a one-time setup phase before ongoing work begins
Seeing constructors as a setup phase like project kickoff helps appreciate their role in preparing contracts for reliable operation.
Common Pitfalls
#1Trying to call the constructor after deployment to reset contract state.
Wrong approach:contractInstance.constructor(); // Attempt to call constructor again
Correct approach:// Use a separate function with access control to reset state if needed function reset() public onlyOwner { // reset logic here }
Root cause:Misunderstanding that constructors run only once and cannot be called later.
#2Not calling parent constructors explicitly in inherited contracts.
Wrong approach:contract Child is Parent { constructor() { // missing Parent constructor call } }
Correct approach:contract Child is Parent { constructor() Parent() { // Parent constructor called explicitly } }
Root cause:Assuming parent constructors run automatically without explicit calls.
#3Including heavy logic in constructor causing high deployment gas cost.
Wrong approach:constructor() { // complex loops or heavy computations }
Correct approach:constructor() { // minimal setup } function initializeHeavy() public onlyOwner { // heavy logic here }
Root cause:Not realizing constructor code runs during deployment and affects gas cost.
Key Takeaways
Constructor functions run exactly once during contract deployment to set initial state.
They cannot be called again after deployment, protecting contract integrity.
Constructor code is removed from the deployed contract, saving gas and storage.
In inheritance, parent constructors must be called explicitly to initialize all parts.
Understanding constructors is essential for secure, efficient, and flexible smart contract design.