Note that there are some explanatory texts on larger screens.

plurals
  1. POClasses and Pointers, how do they work?
    primarykey
    data
    text
    <p>The main issue is with creating a dynamic class. What I did:</p> <pre><code>ptr = new animal[2]; </code></pre> <p>I'm trying to create a dynamic array of size 2, pointed by the pointer ptr. The issue arises when I try these operations:</p> <pre><code>ptr[0].setspeed(9); ptr++-&gt;setspeed(13); </code></pre> <p>I am using DDD (gdb graphical) debugger and when I display ptr, I only see it pointing to one object. When I try to set the speed, the first one seems to work, but the second one won't (the speed is on the default of 0). Printing only gets garbage.</p> <p>I am not so sure what's going on, please help.</p> <p>Also when I do:</p> <pre><code>ptr-&gt;print(); </code></pre> <p>Is it supposed to print for both <code>ptr[0]</code> and <code>ptr[1]</code>, or just <code>ptr[0]</code>?</p> <p>Also, can someone quickly draw a picture of how the <code>ptr</code> and new dynamic class look like? The way I see it, it is a ptr pointing to an array, array size of two, each one has an animal object.</p> <pre><code>#include &lt;iostream&gt; using namespace std; class animal { private: int speed; double position_x; double position_y; public: animal() : speed(0), position_x(0), position_y(0) { } animal (int v, double x, double y) { this-&gt;speed = v; this-&gt;position_x = x; this-&gt;position_y = y; } animal(const animal &amp; g) { this-&gt;speed = g.speed; this-&gt;position_x = g.position_x; this-&gt;position_y = g.position_y; } ~animal(); void print(); int getspeed() { return this-&gt;speed; } int getx() { return this-&gt;position_x; } int gety() { return this-&gt;position_y; } void setspeed(int s) { this-&gt;speed = s; } }; void animal::print() { cout &lt;&lt; "speed: " &lt;&lt; this-&gt;getspeed() &lt;&lt; endl; cout &lt;&lt; "position_x: " &lt;&lt; this-&gt;getx() &lt;&lt; endl; cout &lt;&lt; "position_y: " &lt;&lt; this-&gt;gety() &lt;&lt; endl; } int main() { animal *ptr; ptr = new animal; ptr = new animal [2]; ptr[0].setspeed(9); ptr++-&gt;setspeed(13); ptr-&gt;print(); cout &lt;&lt; ptr[0].getspeed() &lt;&lt; endl; cout &lt;&lt; ptr[1].getspeed(); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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