[Ethereum] Using constructor() and the fallback function in the same contract gives error

constructorcontract-designcontract-developmentfallback-functionsolidity

I'm trying to compile something that mirror a pattern like this and getting the following error from remix:

"browser/ballot.sol:26:3: DeclarationError: Function with same name and arguments defined twice.
constructor() public {
^ (Relevant source part starts here and spans across multiple lines).
browser/ballot.sol:31:3: Other declaration is here:
function() public payable {}
^————————–^"

the code (if I comment out the second fallback function, it works):

pragma solidity ^0.4.0;

contract C {

  address public owner; 
  address public creator;

  constructor (address _creator) public {
    owner = tx.origin;
    creator = _creator;
  }

  function() public payable {}

  function printOwner() public view returns(address h) {
      h = owner;
  }

}

//factory contract for C
contract CFactory {
  address public owner;
  address public currentContractAddress;

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

  //function() public payable {}

  function test1() public returns(address){
    C c = new C(currentContractAddress);
    return c.printOwner();
  }

}

Best Answer

The problem is it doesn't compile.

constructor. This is wrong. In solc 0.4.22 you can say function constructor() but is new (today) so I used the more traditional "same name as contract" method.

tx.orgin is a security risk, so changed to msg.sender with a pass-through pattern.

pragma solidity ^0.4.17;

contract C {

  address public owner; 
  address public creator;

  function C(address _creator, address _owner) public {
    owner = _owner;
    creator = _creator;
  }

  function() public payable {}

  function printOwner() public view returns(address h) {
      h = owner;
  }

}

//factory contract for C
contract CFactory {
  address public owner;
  address public currentContractAddress;

  function CFactory() public {
    owner = msg.sender;
    currentContractAddress = address(this);
  }

  //function() public payable {}

  function test1() public returns(address){
    C c = new C(currentContractAddress, msg.sender);
    return c.printOwner();
  }

}

Hope it helps.

Related Topic