Why can't I set the owner variable to msg.sender instead of using constructor?

I’m following Ethereum Smart Contract Programming 101 and at the video about require, he creates a variable called owner with the type address:

address owner;

Then he makes a constructor function and sets the owner variable to msg.sender.

address owner;
    
constructor() {
    owner = msg.sender;
 }

I’m really confused at that part; why can’t I just set owner to msg.sender in the variable? Like this:

address owner = msg.sender;

Thank you!

msg.sender takes the value of the address who calls functions in the contract. This is true for every address that calls.
For security reasons, You don t want the value of the state variable owner to change.
constructor is a special function that will run only once, when the contract is deployed.
so it will set up only once the value of the owner variable when the contract is deployed

3 Likes

That makes a lot more sense now. Thank you @Sieg!

1 Like

You most welcome @Crownie !

1 Like