Bird
Raised Fist0
Blockchain / Solidityprogramming~15 mins

Constructor function in Blockchain / Solidity - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1.

What is the main purpose of a constructor function in a blockchain smart contract?

easy
A. To execute code every time a function is called
B. To destroy the contract and remove it from the blockchain
C. To set initial values when the contract is deployed
D. To transfer tokens between users

Solution

  1. Step 1: Understand the role of constructor

    A constructor runs only once when the contract is deployed to set initial values.
  2. Step 2: Compare with other functions

    Other functions run multiple times; constructor is special for initialization only.
  3. Final Answer:

    To set initial values when the contract is deployed -> Option C
  4. Quick Check:

    Constructor sets initial values = B [OK]
Hint: Constructor runs once at deployment to set starting values [OK]
Common Mistakes:
  • Thinking constructor runs on every function call
  • Confusing constructor with regular functions
  • Believing constructor can be called multiple times
2.

Which of the following is the correct syntax to declare a constructor in Solidity?

contract MyContract {
    ? {
        // initialization code
    }
}
easy
A. function constructor() public
B. constructor() public
C. def constructor()
D. init() public

Solution

  1. Step 1: Recall Solidity constructor syntax

    In Solidity, the constructor is declared with the keyword constructor() without the function keyword.
  2. Step 2: Check options for correct syntax

    constructor() public matches the correct syntax: constructor() public. function constructor() public wrongly uses function constructor(), which is outdated. def constructor() uses Python syntax. init() public uses a wrong name.
  3. Final Answer:

    constructor() public -> Option B
  4. Quick Check:

    Solidity constructor uses 'constructor()' keyword = C [OK]
Hint: Use 'constructor()' keyword without 'function' in Solidity [OK]
Common Mistakes:
  • Using 'function constructor()' which is deprecated
  • Using other function names like 'init()'
  • Mixing syntax from other languages
3.

What will be the output of the following Solidity contract after deployment?

contract Simple {
    uint public value;
    constructor(uint _value) {
        value = _value;
    }
}

Assuming the contract is deployed with _value = 42, what is the value of value?

medium
A. 42
B. Compilation error
C. Undefined
D. 0

Solution

  1. Step 1: Understand constructor parameter usage

    The constructor takes _value and assigns it to the state variable value.
  2. Step 2: Check deployment argument effect

    Since the contract is deployed with _value = 42, value will be set to 42.
  3. Final Answer:

    42 -> Option A
  4. Quick Check:

    Constructor sets value to 42 at deployment = D [OK]
Hint: Constructor sets state variables from deployment arguments [OK]
Common Mistakes:
  • Assuming default zero value instead of passed value
  • Thinking constructor runs after deployment
  • Confusing variable names
4.

Identify the error in this Solidity contract constructor:

contract Test {
    uint public x;
    constructor() {
        x = 10
    }
}
medium
A. Constructor cannot assign values to variables
B. Constructor name should be Test
C. State variable x is not declared correctly
D. Missing semicolon after x = 10

Solution

  1. Step 1: Check Solidity syntax rules

    Each statement must end with a semicolon ;. The line x = 10 is missing a semicolon.
  2. Step 2: Verify constructor naming

    Since Solidity 0.4.22+, constructors use the constructor() keyword, so naming is correct.
  3. Final Answer:

    Missing semicolon after x = 10 -> Option D
  4. Quick Check:

    Statements need semicolons in Solidity = A [OK]
Hint: Always end Solidity statements with semicolon [OK]
Common Mistakes:
  • Using old constructor naming style
  • Forgetting semicolons
  • Thinking constructor can't assign variables
5.

You want to create a smart contract that stores an owner address set only once during deployment and cannot be changed later. Which constructor code snippet correctly achieves this?

contract OwnerContract {
    address public owner;
    ?
}
hard
A. constructor() { owner = msg.sender; }
B. function OwnerContract(address _owner) { owner = _owner; }
C. constructor(address _owner) { owner = _owner; }
D. constructor() { owner = address(0); }

Solution

  1. Step 1: Understand owner initialization best practice

    Setting owner = msg.sender in the constructor assigns the deployer's address as owner once.
  2. Step 2: Evaluate options

    constructor(address _owner) { owner = _owner; } requires passing owner address manually, which is possible but less secure. function OwnerContract(address _owner) { owner = _owner; } uses old constructor syntax. constructor() { owner = address(0); } sets owner to zero address, which is invalid. constructor() { owner = msg.sender; } correctly sets owner to deployer address.
  3. Final Answer:

    constructor() { owner = msg.sender; } -> Option A
  4. Quick Check:

    Use msg.sender in constructor to set owner = A [OK]
Hint: Use msg.sender in constructor to set owner securely [OK]
Common Mistakes:
  • Using old constructor syntax
  • Setting owner to zero address
  • Passing owner address manually risking errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard