1
votes

I'm a solidity beginner. I'm wondering why should I use constructor. Is it for declaring data type? Here are two examples I made. And both work the same way, and implement the same result.

//--without constructor
pragma solidity 0.5.1;

contract MyContract {
   mapping(address => uint256) public balances;
   address payable wallet;


function buyToken() public payable {
    balances[msg.sender] += 1;
    wallet.transfer(msg.value);

   }
}

//------------ with constructor
pragma solidity 0.6.5;

contract MyContract {
    mapping(address => uint256) public balances;
    address payable wallet;

constructor(address payable _wallet) public {
    wallet = _wallet; //I don't know why they did "wallet = _wallet;"...it seems very inconvenient..
   }

function buyToken() public payable {
    balances[msg.sender] += 1;
    wallet.transfer(msg.value);

   }
}

Even though they work in the same way, why do I need constructor. Please give me lesson.

1

1 Answers

1
votes

Constructor is the same as in other programming languages, especially in object oriented ones:

https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)

A Solidity constructor is called once when a new instance of a smart contract is deployed in Ethereum blockchain.