0

This is simple smart contract for election of two candidates :

pragma solidity 0.4.24;

contract Election {
    //Model a candidate
    struct Candidate{
        uint id;
        string name;
        uint voteCount;
    }
    //Store Candidates
    //Fetch Candidate
    mapping(uint=>Candidate)public candidates;
    //Store Candidates Count
    uint public candidateCount;
    function election()public{
        addCandidate("Donald Trump");
        addCandidate("Barak Obama");
    }

    function addCandidate(string memory _name)private{
        candidateCount++;
        candidates[candidateCount] = Candidate(candidateCount,_name,0);
    }
}  

Why the output is the default output ? Is the value that i'm passing is invalid ?

enter image description here

1
  • Is this a constructor 'election()'? Commented Dec 4, 2018 at 13:58

1 Answer 1

1

If you meant to make a constructor, which add the candidates, then your constructor syntax election() is wrong. Change it into the following

constructor()public{
    addCandidate("Donald Trump");
    addCandidate("Barak Obama");
}

This constructor will be invoked when you deploy your contract, thus adding the two candidates.

6
  • I acctually just changed in my code the 'election' to 'Election'. At first i used capital letter, just my VScode showed me the error like: Functions are not allowed to have the same name as the contract. If you intend this to be a constructor, use "constructor(...) { ... }" to define it. This declaration shadows an existing declaration.
    – Stanley
    Commented Dec 4, 2018 at 14:16
  • So i changed to small 'election'
    – Stanley
    Commented Dec 4, 2018 at 14:16
  • That Cause the default output
    – Stanley
    Commented Dec 4, 2018 at 14:17
  • But i tried your method too, making a constructor instead of a function Election, and it work as well. Do u know why ?
    – Stanley
    Commented Dec 4, 2018 at 14:18
  • The syntax for making constructor is changed to this. Commented Dec 4, 2018 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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