Note that there are some explanatory texts on larger screens.

plurals
  1. POPointers to a class within void function
    text
    copied!<p>I am learning how classes/inheritances/pointers work in C++ and coding the following. </p> <p>I have a class <strong>unit</strong> declared as such:</p> <pre><code>class unit{ public: int locationX,locationY; //genotype (does not change) float agility, build,size,stamina, aggression; //phenotype (changes based on genotype and stimuli) float speed, strength, hunger; }; </code></pre> <p>When I create a new instance to pass into a void function (below, respectively), the memory is not allocated yet.</p> <p><strong>Instance</strong></p> <pre><code>unit **units = 0; </code></pre> <p><strong>Void Function Prototype</strong></p> <pre><code>void initialize(grid *grids, unit **units /*, plant **plants, predator **predators */); </code></pre> <p>The memory is allocated within the void function using some parameters:</p> <pre><code>void initialize(grid *grids, unit **units,plant **plants,predator **predators) { units = new unit*[int(((grids-&gt;gridHeight)*(grids-&gt;gridWidth)*(grids-&gt;gridDivision))/20)]; for(register int i = 0; i&lt;int(((grids-&gt;gridHeight)*(grids-&gt;gridWidth)*(grids-&gt;gridDivision))/20); i++) { units[i] = new unit; units[i]-&gt;hunger = 5; units[i]-&gt;locationX = (rand()%((grids-&gt;gridWidth)-0)); units[i]-&gt;locationY = (rand()%((grids-&gt;gridHeight)-0)); //etc, etc } } </code></pre> <p>However, once I exit the void function, the data I just stored gets deleted. Is there something wrong with the pointer declarations and passing into the function (which is as follows)?</p> <pre><code>initialize(&amp;environment, units, plants, predators); </code></pre> <p><strong>NOTE</strong>: I only have problems with the <em>units</em> variable declared under <strong>unit</strong> class. The <em>environment</em> variable is fine. The other two (<em>plants</em> and <em>predators</em>) are similar to <em>units</em>, so if this is fixed, I can fix the others.</p> <p><strong>Second Note</strong>: The main function is as follows (relevant parts):</p> <pre><code>int main() { unit **units = 0; //&lt;--- Important one plant **plants = 0; predator **predators = 0; grid environment(250,250,5); //Constructor for environment (don't mind this) initialize(&amp;environment, units, plants, predators); //&lt;-- Void function running = true; return 0; } </code></pre> <p>Thank you for any help/links/explanations you can provide.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload