5.2 Dynamic Memory Allocate Object in C++

sunghoon·2025년 3월 16일
0

2.0 Glove Project

목록 보기
15/35
post-thumbnail

5.2.1 make object in heap segmen

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)
  1. declare object pointer
    mousePoint *pt;
  2. allocate object throgh new operator and pointer variable assigned object address
    pt = 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;
}

5.2.2 array of object pointers

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];
  }
}
profile
프라다 신은 빈지노와 쿠페를 타는 꿈을 꿨다.

0개의 댓글