If your method:
removeall()
is supposed to have similar functionality to a destructor (as in it will free allocated memory), then in your case, I think it would be better to call
removeall()
from the destructor instead of vice versa.
1 2 3 4 5 6 7 8 9 10
|
name::~name()
{
removeall();
}
int name::removeall()
{
delete someMember;
return 1;
}
| |
This is similar to what happens in std::ifstream's constructor:
1 2 3 4 5
|
ifstream::ifstream(string filename)
{
open(filename);
}
void ifstream::open(string filename) { ... }
| |
The constructor and open have similar functionality. Instead of calling the constructor from open(), they call open() from the constructor. That will let us make use of the code reuse.
I actually commonly use this sort of thing when I making a controller that needs to be totally reset:
1 2 3 4 5 6 7 8 9 10
|
class PID
{
protected:
init(); // Allocates memory
exit(); // De-allocates memory
public:
PID() { init(); }
~PID() { exit(); }
Reset() { exit(); init(); }
};
| |
The other advantage of putting your code inside of methods instead of constructors or destructors is that ctor/dtors are not inherited. If you want someone to inherit this functionality, then keep that code out of a constructor/destructor.
The only disadvantage that I see is that you can't make use of the initialization lists this way and you have to rely on assignments.
Edit: Thanks
ne555