Say I have a large class, containing dozens of individual member data which needs to be reset to 0 as soon as the class is constructed. Obviously, one could reset each individual member data to 0 via the constructor...
class MyClass
{
public:
MyClass(void);
~MyClass(void) {};
int Data1, Data2, Data3; /* ...and so on... */
};
MyClass::MyClass(void)
{Data1 = Data2 = Data3 = 0; /* ...and so on... */ }
However, if I were to edit the class and add or remove member data, I would have to sync the changes in the constructor where the individual member data is initialized. The method can be *very* tedious if I need to manage lots of things in the class. So I was in the habit of using memset() in the constructor to nuke everything to 0 automatically:
MyClass::MyClass(void)
{memset(this, 0, sizeof(class MyClass)); }
It's a bad habit. Yes I know. (Some Cpp purists would probably crucify me for doing it.) It's been said there is no quarantee the "this" pointer is defined while the constructor is being called, plus memset() will obliterate "hidden" pointer tables if you declare virtual member functions.
Another method is to placing memset() inside a speparate member function, say...
MyClass::Reset(void)
{memset(this, 0, sizeof(class MyClass)); /* ok to use if no vitual functions are declared */ }
...then call it externally after the MyClass::MyClass() constuctor is finished. The only drawback is that it removes the benefit of "automated" initialization like you see with constructors.
Is there a funky way of automatically (and safely) clearing a *large* class without resorting to tedious constructor maintenance or memset() hacks? Suggestions appreciated!