The main issue is with creating a dynamic class. What I did:
ptr = new animal[2];
I'm trying to create a dynamic array of size 2, pointed by the pointer ptr. The issue arises when I try these operations:
ptr[0].setspeed(9);
ptr++->setspeed(13);
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.
I am not so sure what's going on, please help.
Also when I do:
ptr->print();
Is it supposed to print for both ptr[0]
and ptr[1]
, or just ptr[0]
?
Also, can someone quickly draw a picture of how the ptr
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.
#include <iostream>
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->speed = v;
this->position_x = x;
this->position_y = y;
}
animal(const animal & g)
{
this->speed = g.speed;
this->position_x = g.position_x;
this->position_y = g.position_y;
}
~animal();
void print();
int getspeed() { return this->speed; }
int getx() { return this->position_x; }
int gety() { return this->position_y; }
void setspeed(int s) { this->speed = s; }
};
void animal::print()
{
cout << "speed: " << this->getspeed() << endl;
cout << "position_x: " << this->getx() << endl;
cout << "position_y: " << this->gety() << endl;
}
int main()
{
animal *ptr;
ptr = new animal;
ptr = new animal [2];
ptr[0].setspeed(9);
ptr++->setspeed(13);
ptr->print();
cout << ptr[0].getspeed() << endl;
cout << ptr[1].getspeed();
return 0;
}