It will have at least the following member functions:Constructor: Does not receive parameters, and its body simply assigns a specific value to one member field. Destructor: Simply calls the End() member funcion
bool Init(...); // Whatever initialization parameters actually needed. void End(); // No parameters and no return value for finalization. bool IsOk() const; // Typically will be inlined. |
---- File InitEndTest.h ----
class CInitEndTest
{
public:
CInitEndTest (): m_bOk(false) { }
~CInitEndTest () { End(); }
bool Init (parameters);
void End ();
bool IsOk () const { return m_bOk; }
void DoStuff ();
private:
bool m_bOk;
};
---- File InitEndTest.cpp ----
#include "InitEndTest.h"
bool CInitEndTest::Init(parameters)
{
End();
// ... perform initializations
// ... set m_bOk to true if everything goes right.
return m_bOk;
}
void CInitEndTest::End()
{
if (m_bOk)
{
// Free resources.
m_bOk = false;
}
}
void CInitEndTest::DoStuff()
{
ASSERT(IsOk());
// Actually do the stuff
}
---- End of sample ----
|
---- File VirtualTest.h ----
#include "InitEndTest.h"
class CVirtualTest: public CInitEndTest
{
typedef CInitEndTest inherited; // To avoid the actual base's name.
public:
CVirtualTest () { }
virtual ~CVirtualTest () { End(); }
bool Init (parameters);
virtual void End ();
private:
};
---- File VirtualTest.cpp ----
#include "VirtualTest.h"
bool CVirtualTest::Init(parameters)
{
End();
// Initialize the base first.
if (inherited::Init())
{
// ... perform my own initializations
// ... call inherited::End() if they fail.
}
return IsOk();
}
/*virtual*/ void CVirtualTest::End()
{
if (IsOk())
{
// Free my own resources
// Free the base's at the end.
inherited::End();
}
}
---- End of sample ----
|