Dynamic Allocation for Instance Variable

Can I do this?
I have a class Image. In this class, I have a instance variable of pointer float *h. But I do not initialize this pointer in constructor. I initialize this pointer in function hist which performs h= new float(L_LUM)//L_LUM =256;

1
2
3
4
5
6
class Image{
    float *h;
}
float *ImageGS::hist(int x){
	h = new float[L_LUM];
}
Yes that is perfectly acceptable. Although if you want proper encapsulation, you should take various precautions.

1) set the pointer to NULL in your constructor to indicate that no memory has been allocated for it

2) Write a proper Copy Constructor and assignment operator which deep copy the pointer. Or if you don't want that, just make the copy ctor/assignment private with no body to forbid object copying

3) delete[] the buffer in your destructor

4) Prevent 'h' from being allocated multiple times if 'hist' is called when 'h' has already been allocated. Either that or delete[] the old h and reallocate it.



Of course, all of this extra work can be avoided if you use a container class like a vector.

Furthermore, if L_LUM is a constant, there's no reason to use dynamic memory here anyway (unless it's a very large constant). You can just use a normal array.
Topic archived. No new replies allowed.