Solidity Compiler Error – Fixing Error: Use ‘constructor(…) {…}’ Instead

compilersolidity

I've followed the lecture on Udemy. But I've got an error

here's my 'Inbox/contracts/Inbox.sol'

pragma solidity ^0.4.17;
contract Inbox {
    string public message;

    function Inbox(string initialMessage) public {
        message = initialMessage;
    }

    function setMessage(string newMessage) public {
        message = newMessage;
    }
}

and here is a 'Inbox/compile.js' file

const path = require('path');
const fs = require('fs');
const solc = require('solc');

const inboxPath = path.resolve(__dirname, 'contracts','Inbox.sol');
const source = fs.readFileSync(inboxPath, 'utf8');

console.log(solc.compile(source, 1));

and after I compile this file on terminal

node compile.js

got an error like below

  errors: 
           [ ':6:5: Warning: Defining constructors as functions with the same name 
as the contract is deprecated. Use "constructor(...) { ... }" 
    instead.\n    function Inbox(string initialMessage) public {\n    ^ 
    (Relevant source part starts here and spans across multiple lines).\n' ],

I use mac.
One thing I did differently from the lecture was 'npm init' in other folder instead of Inbox and
I coppied and pasted all the files created to inbox folder.

Best Answer

It should be a warning not an error. Anyway using this syntax

function Inbox(string initialMessage) public {
    message = initialMessage;
}

is deprecated in the newer version of Solidity. You have to use constructor instead of the contract name

constructor(string initialMessage) public {
    message = initialMessage;
}

this will compile without warnings

Related Topic