Consider the following Solidity contract snippet. What will be the output when callPublic() is called?
pragma solidity ^0.8.0; contract VisibilityTest { string private secret = "hidden"; string public info = "visible"; function getSecret() private view returns (string memory) { return secret; } function callPublic() public view returns (string memory) { return info; } }
Remember that public variables create getter functions accessible externally.
The info variable is declared public, so calling callPublic() returns its value "visible". The private function getSecret() is not called here.
What happens if an external caller tries to call the private function getSecret() from the contract below?
pragma solidity ^0.8.0; contract VisibilityTest { string private secret = "hidden"; function getSecret() private view returns (string memory) { return secret; } }
Private functions are only callable inside the contract.
Private functions cannot be called from outside the contract, so trying to call getSecret() externally causes a compilation error.
Given the following contracts, what will Derived.getInternal() return?
pragma solidity ^0.8.0; contract Base { string internal data = "base data"; function getData() internal view returns (string memory) { return data; } } contract Derived is Base { function getInternal() public view returns (string memory) { return getData(); } }
Internal functions are accessible in derived contracts.
The internal function getData() is accessible inside the derived contract Derived, so calling getInternal() returns "base data".
Consider this contract. What will happen if callExternal() is called?
pragma solidity ^0.8.0; contract VisibilityTest { function externalFunc() external pure returns (string memory) { return "external called"; } function callExternal() public view returns (string memory) { return externalFunc(); } }
External functions require a special call syntax when called internally.
External functions cannot be called internally by simple function call syntax. They must be called using this.externalFunc(). Otherwise, it causes a compilation error.
Choose the visibility modifier that restricts function access to the contract itself and any contracts that inherit from it, but disallows external calls.
Think about which modifier allows inheritance access but blocks external calls.
internal functions and variables are accessible inside the contract and in derived contracts, but not from outside. private restricts access only to the contract itself.