As we know that every time when we declare a class with initial C and derive from CBase we have to provide second phase constructor (NewL and NewLC ) in genral for such classes. There is a way which will give some flexibility to reduce to write NewL and NewLC evey time when you derive a class from CBase and need second phase constructor.
//Define a class which is base class like this:
//Phasebase.h base class for all classes derived from CBase
//and has second phase constructor
#include <e32def.h>
#include <e32base.h>
template <class T>
class CPhaseBase : public CBase
{
public:
static T* NewL()
{
T* self = new (ELeave) T();
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::Pop(self);
return self;
}
static T* NewLC()
{
T* self = new (ELeave) T();
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
public:
//All classes derive from CPhasebase must implement this function
virtual void ConstructL() = 0 ;
};
and here is an example class which uses this class as base class
//UsePhase.h
#include "Phasebase.h"
class CUsePhase;
class CUsePhase : public CPhaseBase<CUsePhase>
{
private:
HBufC* iMyBuf;
public:
void ConstructL();
public:
CUsePhase()
{
}
~CUsePhase();
};
//UsePhase.cpp
#include "UsePhase.h"
#define KMaxLength 50
void CUsePhase :: ConstructL()
{
iMyBuf = HBufC::NewL(KMaxLength);
}
CUsePhase ::~CUsePhase()
{
if(iMyBuf)
{
delete iMyBuf;
iMyBuf = NULL;
}
}
To use the class you simply need to do:
CUsePhase *iMyPhase;
iMyPhase = CUsePhase::NewL();
This will call templated NewL of CPhaseBase class and internally calls ConstructL of CUsePhase which is second phase constructor.
Note: if you want parameterized constructors then you must override NewL and NewLC and then from that has to call NewL of CPhaseBase.
Bhuvan.
|