DEV Community

Cover image for Day 20 - Constructors
Vedant Chainani
Vedant Chainani

Posted on • Edited on

Day 20 - Constructors

GitHub logo Envoy-VC / 30-Days-of-Solidity

30 Days of Solidity step-by-step guide to learn Smart Contract Development.

This is Day 20 of 30 in Solidity Series
Today I Learned About Constructors in Solidity.

A constructor is a special method in any object-oriented programming language which gets called whenever an object of a class is initialized. It is totally different in case of Solidity, Solidity provides a constructor declaration inside the smart contract and it invokes only once when the contract is deployed and is used to initialize the contract state. A default constructor is created by the compiler if there is no explicitly defined constructor

Creating a constructor

A Constructor is defined using a constructor keyword without any function name followed by an access modifier. It’s an optional function which initializes state variables of the contract. A constructor can be either internal or public, an internal constructor marks contract as abstract.

Syntax:

constructor() <Access Modifier> {          
} 
Enter fullscreen mode Exit fullscreen mode

Following are the key characteristics of a constructor.

  • A contract can have only one constructor.

  • A constructor code is executed once when a contract is created and it is used to initialize contract state.

  • After a constructor code executed, the final code is deployed to blockchain. This code include public functions and code reachable through public functions. Constructor code or any internal method used only by constructor are not included in final code.

  • A constructor can be either public or internal.

  • A internal constructor marks the contract as abstract.

Example:

pragma solidity ^0.8.7;

contract constructorExample {
    string str;

    // Creating a constructor to set value of 'str'
    constructor() public {
        str = "Example Constructor";
    }

    // Defining function to return the value of 'str'
    function getValue() public view returns (string memory) {
        return str;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)