Since you are asking, I originally read somewhere (perhaps in this forum?) that, when using the new operator, it is a good idea to do it outside of the constructor, since new could fail.
Later however, I found out that I really don't want my program to continue execution if my "new" fails. I also found out that I dont really wanna do error catching code, since the system does well enough on informing you you messed up :).
However, the "init" functions remained in my code. The reason there was no "delete" before the "new" in my "init" function (like there always should be) was that I hadn't figured that out in the "restart" (asuming it ever began) of my c++ "carier" a couple of months ago...
class foo
{
int* ptr;
void init(); // here to show some init is done on constructor
public:
foo(int s) {ptr =newint[s]; init();}
~foo() {delete[] ptr;}
}
If an exception is thrown out of the constructor, then the foo object is not fully formed so it's destructor will not be called and the memory will be leaked.
You can use a self contained container class such as a vector:
1 2 3 4 5 6 7 8
class bar
{
vector<int> p;
void init(); // here to show some init is done on constructor
public:
bar(int s) : p(s){init();}
//...
}
That way as long as p is fully formed, if the construction of bar craps out, p will be deleted successfully.
Will leak on each call because init() is not checking to see if elements has already been declared, and if so; freeing the memory.
~Selection(){delete [] elements;};
You should check to ensure elements != 0 before deleting the memory. Otherwise you may end up with a crash if your new has failed or init() has no been called.