Constructor and fallback functions
In this recipe, you will learn about two important methods in a contract: constructor
and fallback
functions.
How to do it...
The declaration and workings of these methods are very similar to other object-oriented languages. Let's look into each one individually.
Constructor
The constructor is a function that is executed when a contract is created. It cannot be called explicitly and is invoked only once during its lifetime. Every contract can have exactly one constructor and if no constructor is declared, the contract will use the default constructor.
- Create a constructor in solidity using the
constructor
keyword:
contract A { constructor() { // Constructor } }
- Then, write some logic that should get executed during contract creation inside the constructor:
contract A { address owner; constructor() { owner = msg.sender; } }
- Now, decorate the constructor as either public (default) or internal. A constructor set as internal causes...