Piece of code with constructor

by Pierre   Last Updated August 01, 2020 13:28 PM

Can you explain me what this piece of code does please? i don't understand it at all.

constructor() public { addCandidate("candidate 1"); addCandidate("candidate 2"); } function addCandidate(string name) private { candidateCount += 1; candidates[candidateCount] = Candidate(candidateCount, name, 0); }

Thank you very much

Take care

Tags : solidity


Answers 1


The constructor is a function that is called once, when you deploy a contract to the network. It cannot be called manually, after deployment. This code will run the addCandidate function twice on deployment, which adds new Candidates to the candidates array (or mapping, it's not entirely clear from the snippet you posted).

candidates[candidateCount] = ... basically assigns a value to the array, where the index is candidateCount. If the candidateCount is 0 by default, this will create a candidate for index 1 and 2.

Morten
Morten
August 01, 2020 13:06 PM

Related Questions


How to map an address with a string array in solidity?

Updated October 09, 2018 12:28 PM

How to handle dynamic size string array in solidity?

Updated November 28, 2018 04:28 AM

What is the status of forbidden call in constructor?

Updated December 12, 2018 08:28 AM

How can I pass struct from one contract to another?

Updated January 10, 2019 23:28 PM

How to transfer Ether to ERC20 token contract?

Updated July 23, 2018 00:28 AM