Hi, I have a question about allocating memory in constructor. For example consider simple
class Array:
Code:
#include <iostream>
using namespace std;
class Array
{
double* array;
int len;
public:
Array(int);
void load();
void show();
~Array();
};
Array::Array(int i):len(i)
{
array=new double[len];
}
void Array::load()
{
cout<<"Enter elements: ";
for(int i=0;i<len;i++)
{
cin>>array[i];
}
}
void Array::show()
{
for(int i=0;i<len;i++)
cout<<array[i]<<" ";
}
Array::~Array()
{
delete [] array;
}
int main()
{
Array a(5);
a.load();
a.show();
}
I've read somewhere that it's not good to have new in constructor because there is a possibility that under some circumstances process of memory allocation fails. In that case object will not be created in a propery way. How to handle this case? Should I write for example a new method create() and in constructor to leave just:
Code:
Array::Array(int i):len(i)
{
}
Beacuse many of you have a lot more experience then I have I'm sure you're going to give me some good advices on this issue.
Thanks very much!