How object allocate dynamic memory
it need “object pointer variable” to allocate memory in heap segment. class type momory create through new operator and then new
pass address value
mousePoint *pt;
pt = new MousePointer(10, 20)
mousePoint *pt;
new
operator and pointer variable assigned object addresspt = new MousePoint(10, 20)
#include <iostream>
using namespace std;
class MousePoint {
public:
MousePoint();
MousePoint(int nX, int xY);
void SetXY(int X, int Y);
int GetX() const;
int GetY() const;
private:
int x, y;
};
MousePoint::MousePoint() {}
MousePoint::MousePoint(int nX, int nY) {
x = nX;
y = nY;
}
void MousePoint::SetXY(int nX, int nY) {
x = nX;
y = nY;
}
int MousePoint::GetX() const { return x; }
int MousePoint::GetY() const { return y; }
int main() {
MousePoint *pt;
pt = new MousePoint(10, 20);
cout << "X coordinate: " << pt->GetX() << ", "
<< "Y coordinate: " << pt->GetY() << endl;
delete pt;
return 0;
}
Can allocate lot a object point as Array and it can create object on dynamic memory. it’s called “Array of Object Pointers”.
// on the stack
MousePointer *pArr[3];
// on the heap
pArr[0] = new MousePointer(10, 20);
pArr[1] = new MousePointer(100, 200);
pArr[2] = new MousePointer(1000, 2000);
#include <iostream>
using namespace std;
class MousePoint {
public:
MousePoint();
MousePoint(int nX, int xY);
void SetXY(int X, int Y);
int GetX() const;
int GetY() const;
private:
int x, y;
};
MousePoint::MousePoint() {}
MousePoint::MousePoint(int nX, int nY) {
x = nX;
y = nY;
}
void MousePoint::SetXY(int nX, int nY) {
x = nX;
y = nY;
}
int MousePoint::GetX() const { return x; }
int MousePoint::GetY() const { return y; }
int main() {
MousePoint *pArr[3];
pArr[0] = new MousePoint(10, 20);
pArr[1] = new MousePoint(100, 200);
pArr[2] = new MousePoint(1000, 2000);
for(int i =0; i < 3; i++) {
cout << pArr[i]->GetX() << ", " << pArr[i]->GetY() << endl;
}
for(int i =0; i < 3; i++) {
delete pArr[i];
}
}