Solidity: Constructor function needs to be always "public"?

Viewed 204

In solidity, while relating a "withdraw" function to be only callable from the admin contract, the "construct" comes handy.

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

Question: How come it has to be set as a "public" function? As we want no one but us to trigger the withdraw, shouldn´t it be entered as "internal" or "private"?

2 Answers

the constructor is just triggered on deploy so no one else can call it before the deploy, it can be public and you will have no problems but in most recent solidity versions is not necessary to mark the constructor as public

A withdraw function should be marked as public or external for you, or its non-contract owner, to be able to withdraw it. Why? If you mark a function as private, only the functions inside the smart contract will be able to interact with it, and by marking a function as internal, functions inside a contract and contracts that inherit from this one will be able to call the function. Why you probably want to make it this way? Because you, as a normal user, wont be able to call this function directly. So by making this function public or external, every user will be able to interact with the function. And here is your question.

How come it has to be set as a "public" function? As we want no one but us to trigger the withdraw, shouldn´t it be entered as "internal" or "private"?

You can set the function as public and create a require statement (it can be a modifier or a conditional "if", as you want.) and just check if the remitent is the owner. And only if it is, then withdraw. Here is an example:

function withdraw() public {
    require(msg.sender == owner, "Only the owner can call this function.");

    // Withdraw logic here.
}

Hope you find this useful :)

Related