Constructors in Solidity

What is a Constructor in Solidity?

Solidity is very similar to languages like Javascript and Python, let's take a look at how constructors work in Javascript and then compare them.

Constructors in Javascript are a part of Object-Oriented Programming. A constructor is basically a function in Javascript that is usually called an "object". A constructor gets called whenever you use the keyword 'new'. The main use of a constructor is to create an object and set the values of the properties present in that object.

Let's take a look at the syntax for writing a syntax in Javascript

function createUser (first, last){
this.firstName = first;
this.lastName = last;
};
var newUser1 = createUser("Aditya", "Singham");
console.log(newUser1);
// expected output: Aditya Singham
var newUser2 = createUser("Jon", "Snow");
console.log(newUser2);
// expected output: Jon Snow

As you can see we are calling the constructor in the function createUser, then we are updating the values using the 'this' keyword. After this we can keep calling the function as many times we want with the updated values and we will keep getting new outputs.

Constructors in Solidity

Constructors in Solidity work entirely different from normal object-oriented programming languages. In other languages, a constructor is initialized whenever it is called using the specific keyword, as we saw above in Javascript this keyword is 'new'. However, in Solidity this is not the case, here the constructor is provided by Solidity and is called only once during the entire compilation and is primarily used to set the state of the smart contract. A constructor is provided by default in Solidity, this means that even if there is no constructor being called explicitly in the smart contract it is provided by default to set the state of the Smart Contract

How to create a Constructor in Solidity:

A constructor can be created in Solidity by using the 'constructor' keyword followed by an Access Modifier. Let's look at the syntax to understand how to exactly create a constructor in Solidity.

constructor () <Access Modifier> {
}

Here is how to use a Constructor in Solidity.

// specifying the version number of Solidity
pragma solidity ^0.5.0;

// creating the contract
contractconstructorExample { // declaring a string variable string str; // declaring the constructor and setting it to public
constructor() public { 
str = "Suyash";
}
// creating a function to get the value of the Constructor
function getValue() public view returns (string memory) {
return str;
}
};
//output: string: Suyash

If you have any more questions you can find me on my Twitter and LinkedIn