In this section, we will introduce constructor
and modifier
in Solidity, using an access control contract (Ownable
) as an example.
Constructor
constructor
is a special function, which will automatically run once during contract deployment. Each contract can have one constructor
. It can be used to initialize parameters of a contract, such as an owner
address:
Note: The syntax of the constructor in solidity is inconsistent for different versions: Before solidity 0.4.22
, constructors did not use the constructor
keyword. Instead, the constructor had the same name as the contract name. This old syntax is prone to mistakes: the developer may mistakenly name the contract as Parents
, while the constructor as parents
. So in 0.4.22
and later versions, the new constructor
keyword is used. Example of constructor prior to solidity 0.4.22
:
Modifier
modifier
is similar to decorator
in object-oriented programming, which is used to declare dedicated properties of functions and reduce code redundancy. modifier
is Iron Man Armor for functions: the function with modifier
will have some magic properties. The popular use case of modifier
is restricting access to functions.

Let's define a modifier called onlyOwner
, functions with it can only be called by owner
:
Next, let us define a changeOwner
function, which can change the owner
of the contract. However, due to the onlyOwner
modifier, only the original owner
is able to call it. This is the most common way of access control in smart contracts.
OpenZeppelin's implementation of Ownable:
OpenZeppelin
is an organization that maintains a standardized code base for Solidity
, Their standard implementation of Ownable
is in this link.
Remix Demo example
Here, we take Owner.sol
as an example.
- compile and deploy the code in Remix.
- click the
owner
button to view the current owner. - The transaction succeeds when the
changeOwner
function is called by the owner address user. - The transaction fails when the
changeOwner
function is called by other addresses.
Summary
In this lecture, we introduced constructor
and modifier
in Solidity, and wrote an Ownable
contract that controls access of the contract.