On 11/4/05 4:51 AM, in article
bp********************************@4ax.com,
"Howie" <ho****@webb.de> wrote:
Hi,
i have a normal class:
//test.h
class CForwardData;
class CTest
{
CForwardData *pData;
public:
//Methods to access the data.
// some other stuff...
CTest::CTest();
CTest::~CTest();
};
//test.cpp
class CForwardData
{
public:
long aLong;
double aDouble;
};
CTest::CTest()
{
pData = new CForwardData;
}
CTest::~CTest()
{
delete pData;
}
//... Methods to access the data............
This is the normal way i am using to hide the data implementation for
any user, who has access only to the *.h files.
Is there a other c++ way to do the same without using the forward
declared class ?
It's possible to use the hidden derived class:
In CTest.h:
class CTest
{
CTest::CTest();
public:
// a factory method
static CTest * CreateCTest();
// the public API goes here
CTest::~CTest();
};
And in CTest.cpp:
class CDerivedTest : public CTest
{
public:
CDerivedTest ();
... // internal API goes here
}
CTest * CTest::CreateCTest()
{
CDerivedTest *theTest = new CDerivedTest;
return theTest;
};
In other words, every client knows that they have a pointer to a CTest
object, but none of them need to know that their CTest pointer is actually
pointing to a class derived from CTest.
For this approach to work, CTest needs a static factory method to create
CTest objects. The client cannot be allowed to create CTests directly.
Generally, a factory method is often a good idea anyway since it allows the
implementation more control over the creation of its objects.
Greg