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.