when I try to enter elements through getData() function, I get error segmentation fault(core dumped). I am not able to enter elements into array. I am not able to understand why i cannot access the memory location returned by void* into Class type. size of *parr is 4 bytes, still I cannot data into that memory location???
#include<iostream>
#include<cstdlib>
using namespace std;
class Array
{
int *arr;
public:
void* operator new(size_t size)
{
void *parr=::new int[size];
//cout<<sizeof(parr);
return parr;
}
void operator delete(void *parr)
{
::delete (int*)parr;
}
void getData()
{
cout<<"Enter the elements";
for(int i=0;i<5;i++)
cin>>arr[i];
}
void showData()
{
cout<<"Array is:\n";
for(int i=0;i<5;i++)
cout<<arr[i];
}
};
int main()
{
Array *A=new Array;
A->getData();
//A->showData();
(*A).showData();
delete A;
return 0;
}
What you probably meant to do instead of overloading the new
and delete
operators for class Array
, is to write appropriate constructor and destructor functions:
class Array {
int *arr;
public:
Array(size_t size) : arr(new int[size]) {
}
~Array() {
delete arr;
}
// ...
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.