How to initialize a state variable using constructor in solidity.

How to initialize a state variable using constructor in solidity.

Constructor is a special keyword used in solidity for initializing state variables, in this article we will look at what constructor is and how to initialize a state variable with it.

Table of content(2).png

State variable

This is a type of variable in solidity , that can be accessed from anywhere inside the contract in which they are being declared.

This is an example of a state variable below

Snap(9).png

Constructor

Constructor is a special keyword in solidity , it is use for initializing state variable inside a contract. In a contract you can only have a single constructor and even in a situation whereby a constructor is not added to a contract it is being added by default.

A constructor is being created with the syntax below.

Snap(10).png

How to initialize a state variable with Constructor

State variables can be initialized by a constructor using the following steps :

(1) declare the constructor keyword

Snap(12).png

(2) open a parenthesis and pass an argument based on the data types of the state variable

Snap(13).png

(3) Set the scope of the constructor (this can either be public or internal)

Snap(14).png

(4) open a curly brackets to assign the state variable to the arguments of the constructor

Snap(15).png

This is a simple step on how to initialize a state variable using constructor , so whatever value that is input inside the constructor argument is the value of the state variable.

My name is eibrahim a blockchain developer and technical writer , i create content and articles to simplify web 3 and blockchain for everyone. Thanks for reading through

You can follow me on Twitter and Hashnode for more simplified blockchain content