5-3 A class that has a pointer member variable in C++

sunghoon·2025년 3월 16일
0

2.0 Glove Project

목록 보기
16/40
post-thumbnail

this time Allocate dynamic memory thorugh pointer on member variable.

5.3.1 Allocate Dynamic memory inside class

Question

/*
Question) create String class
1 step - get two argument char type, int type on constructure. and
2 step - Print an array filled with the input character repeated as many times
as the input integer. (use memset()

e.g
#include <iostream>
using namespace std;

class String {
public:
String(char ch, int num);
~String();
private:
    int size;
    char *pBuffer;
};

String::String(char ch, int num) {
}

String::~String() {
}

int main () {
    String str1('A, 5');

    return 0;
}

*/

#include <iostream>
using namespace std;

class String {
 public:
  String(char ch, int num);
  ~String();

 private:
  int size;
  char *pBuffer;
};

String::String(char ch, int num) {
  size = num;
  pBuffer = new char[size + 1];
  memset(pBuffer, ch, size);
  pBuffer[size] = '\0';

  cout << "pBuffer: " << pBuffer << ", " << "size: " << size << endl;
}

String::~String() { delete pBuffer; }

int main() {
  String str1('A', 5);

  return 0;
}
  • char *pubuffer create pointer member
  • pbuffer = new char[nLength + 1]; create character array on dynamic memory
  • ~String() { delete pBuffer; } delete array on dynamic memory when deconstuct

5.3.2 Assignment Between Objects and Its Issues

#include <iostream>
using namespace std;

class String {
 public:
  String(char ch, int num);
  ~String();

 private:
  char *pBuffer;
};

String::String(char ch, int num) {
  pBuffer = new char[num + 1];
  memset(pBuffer, ch, num);
  pBuffer[num] = '\0';

  cout << "pBuffer: " << pBuffer << ", " << "num: " << num << endl;
}

String::~String() { delete[] pBuffer; } // can't work second destruct 

int main() {
  String str1('A', 5), str2('B', 3);

  str2 = str1;  // err!
  return 0;
}

it’s work duplicate with member that assigned between object. it’s same below code.

str2.nLength = str1.nLength;
str2.pBuffer = str1.pBuffer;

It’s now problem but when destruct make error. second destructure try to destruct again. And it remain origianlly heap memory that str2 had array.

So, We use “Assigment Operator Overloading”

📚 reference
- book - C++ 프로그래밍과 STL (이창현)
-Photo by Aniq Danial on Unsplash

profile
프라다 신은 빈지노와 쿠페를 타는 꿈을 꿨다.

0개의 댓글