envoy1084
/
30-Days-of-Solidity
30 Days of Solidity step-by-step guide to learn Smart Contract Development.
WARNING: This repository is currently undergoing updates and revisions to incorporate the latest information and advancements in Solidity programming. Please be advised that the content may not be up-to-date or accurate during this time. We expect the updates to be completed within the next 30 days, and appreciate your patience during this process. Thank you for your understanding.
Contents
- Day 1 - Licenses and Pragma
- Day 2 - Comments
- Day 3 - Initializing Basic Contract
- Day 4 - Variables and Scopes
- Day 5 - Operators
- Day 6 - Types
- Day 7 - Functions
- Day 8 - Loops
- Day 9 - Decision Making
- Day 10 - Arrays
- Day 11 - Array Operations
- Day 12 - Enums
- Day 13 - Structs
- Day 14 - Mappings
- Day 15 - Units
- Day 16 - Require Statement
- Day 17 - Assert Statement
- Day 18 - Revert Statement
- Day 19 - Function Modifiers
- Day 20…
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> {
}
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;
}
}
Top comments (0)