Quiz Entry - updated: 2026.07.30
What is a constructor in Solidity, and when does it run?
A special function that runs exactly once, automatically, at the moment the contract is deployed — in the same transaction that creates the contract.
address public owner;
constructor() {
owner = msg.sender; // whoever deploys becomes the owner
}
The constructor has no function keyword because Solidity recognises it specially. Its job is to set up the contract's initial state at deployment. A classic use: capture the deployer as the owner. Because the constructor runs in the deployment transaction, msg.sender inside it is the account deploying the contract — so owner = msg.sender permanently records the deployer. This is the foundation for access control ("only the owner may withdraw").
Go deeper:
Solidity docs: constructor — the one-time deployment function and base-constructor arguments.