What is difference between internal and private in Solidity?
Asked Answered
G

4

13

In Solidity we have four types of access. Two of them are private and internal. What is the difference if both of them can be used inside smart contract and both of them are not visible after deploying?

Grapher answered 18/11, 2021 at 12:38 Comment(1)
By not visible after deploying you mean they are not visible (and cannot be used) by a user or another smart contract.Cartogram
G
25

Access types:

public - can be used when contract was deployed, can be used in inherited contract

external can be used when contract was deployed , can NOT be used in inherited contract

internal - can NOT be used when contract was deployed , can be used in inherited contract

private - can NOT be used when contract was deployed, can NOT be used in inherited contract

Grapher answered 2/12, 2021 at 11:22 Comment(1)
This was better than the soildity docsDoggerel
S
17

internal properties can be accessed from child contracts (but not from external contracts).

private properties can't be accessed even from child contracts.

pragma solidity ^0.8;

contract Parent {
    bool internal internalProperty;
    bool private privateProperty;
}

contract Child is Parent {
    function foo() external {
        // ok
        internalProperty = true;
        
        // error, not visible
        privateProperty = true;
    }
}

You can find more info in the docs section Visibility and Getters.

Selffulfillment answered 18/11, 2021 at 15:54 Comment(0)
T
1
  • public: anyone can access the function
  • private: only this smart contract can call this function
  • internal: only this smart contract and smart contracts that inherit from it can call this function
  • external: anyone can access this function unless this smart contract

Note that external uses less gas than public so if the function is not used by your contract, prefer external over public.

Towardly answered 16/12, 2022 at 7:26 Comment(0)
M
1

Although there are thorough answers here, another approach I think we could take about these keywords is that:

  • internal or external mentions the way blockchain see the function, e.g. internal the contract itself, external (outside and only outside) the contract.
  • private or public mentions how the inheritance concept in OOP work in solidity.

Good luck to you all.

Maxma answered 3/1 at 6:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.