Hi all C++ expert,I'm new in this field.I've written a program but I need to write it using class. I'm not able to understand where I'll define
a = new double[numElement];
etc.... and
delete [] a;
etc... I'm confused where and why I'll define 'new' & 'delete' using class,constructor etc. I'm not confident about 'vector' also.So please help me how to solve it I'll really thankful to you.
hey, I'm no expert by any means but I'll share my two cents:
You define variables as "new" then "delete" them when they are created in a function but, need to be available after the function is terminated. What normally happens is when a function creates a variable, it exists for the duration of the function, then is deleted when the function terminates. For a better understanding you'd probably be best to research/understand pointers.
Basically, when you create a "new" variable, it exists (ie the memory allocation exists) until it is "deleted". Just make sure you DO delete any of these variables before every exit point in your program. (I find it easier to make a "deleteVariables()" type function which deletes (and sets to NULL) these variables which I call before exiting.
Your class would probably store a pointer, say double* a;, then what you only need to do is to point to different memory locations to manipulate your data.
The constructor should allocate spaces on the heap (for you to store data in the future). For example, you write a = newdouble[100];, you mean you make 100 neighbouring "holes" in the heap that holds doubles with a pointing to the first hole. (You can later access the data when you give the "offset" from a, like a[10];.)
Because the memory in the heap remains when a function returns, or until the end of the program is reached, you want to "free" the memory spaces when you don't need them anymore. The destructor should then call delete on the pointer, delete [] a;. Note that calling delete on it just frees the memory, the pointer remains as your class variable, so also set it to null a = NULL; to make sure it points to nothing.
Hey mrHappyPants and wmheric, I have solved this problem and also marked.I put all new in constructor & all delete in destructor.Thanks for your kind touch.