0

can we call constructor in another function of the same contract in solidity ? Curious, Kindly reply asap. Thanks

3 Answers 3

0

It is not possible to call the constructor because it is not part of the runtime bytecode.

However it is possible to call a function from the constructor and then it will be available for use at any time.

// SPDX-License-Identifier: ISC

pragma solidity 0.8.14;

contract Test {
     uint256 public x;

     constructor(uint256 _x) {
          _initialize(_x);
     }

     function foo(uint256 bb) public {
          _initialize(bb);
     }

     function _initialize(uint256 _a) internal {
          x = _a;
     }
}
0

Calling the constructor of other contracts is only possible in this way.

contract ERC20{
    mapping(address => uint256) private _balances;
    string public _name;
    string public _symbol;
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
        _balances[msg.sender] = 1000000000E18;
    }
}

contract YToken is ERC20 {
    constructor(string memory name_, string memory symbol_) ERC20(name_, symbol_) {
        
    }
}

as @Ismael has stated it is not possible to call a constructor of an already deployed contract because it is not part of the runtime bytecode.

0

yes, you can use constructors, variables, functions, etc of other contracts of same smart contract. e.g.-

// SPDX-License-Identifier: MIT    
pragma solidity >=0.7.0 <0.9.0;
    
contract c1 {
    uint a;
    constructor(){
        a=100;
    }
}

contract c2 is c1{
    function getA() public view returns(uint){
        return a;
    }
}

use function of another contract:

// SPDX-License-Identifier: MIT    
pragma solidity >=0.7.0 <0.9.0;
    
contract c1 {
    uint a;
    constructor(){
        a=100;
    }
    function changeA(uint _a) public{
        a=_a;
    }
}

contract c2 is c1{
    function getA() public view returns(uint){
        return a;
    }
    function change(uint _a) public{
        changeA(_a);
    }
}

reference docs: https://docs.soliditylang.org/en/develop/contracts.html#inheritance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.