
this time Allocate dynamic memory thorugh pointer on member variable.
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 memberpbuffer = new char[nLength + 1]; create character array on dynamic memory~String() { delete pBuffer; } delete array on dynamic memory when deconstuct#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