PDA

View Full Version : Pimpl implemenation - compilation error on static_cast base* to Derieved*



sunil.thaha
13th September 2007, 09:49
Hi,

I was trying out the pimpl idiom and its implementation in Qt.
I was wondering why the following code gives me an error in the data_pointer_test function. the error happens in both the static and the dynamic cast.

AFAIK, static cast should be able perform a downcast. as the following code does not give me any error


PrivateData *d = new QstObjectPrivate(0);
QstObjectPrivate *back = static_cast<QstObjectPrivate *>( d);
Am I getting the basics wrong ?
Here is the Pimpl implementation code ...


p, li { white-space: pre-wrap; } // --- Private Data ---
class PublicInterface;
class PrivateData {
friend class PublicInterface;
public:
PrivateData( PublicInterface *iface )
:_interface(iface){}
virtual ~PrivateData(){
}
// ---- data ----
PublicInterface *_interface;
};
// --- Public Interface ---
class PublicInterface{
friend class PrivateData;
protected:
inline PublicInterface( PrivateData *d ):_data( d ){
}

inline ~PublicInterface(){
delete _data;
}
// ---- data ----
PrivateData *_data;
};
// --- My Private Test Harness ---
class QstObjectPrivate;
class QstObject : public PublicInterface{
public:
QstObject();
private:
QstObjectPrivate* data_pointer_test() {
return static_cast<QstObjectPrivate*>( _data );
}
};
class QstObjectPrivate : public PrivateData{
public:
QstObjectPrivate( PublicInterface *iface ):PrivateData( iface ){
}
};
QstObject::QstObject()
:PublicInterface( new QstObjectPrivate(this) ){
}
int main(){
QstObject test;
}

sunil.thaha
14th September 2007, 07:33
Is this very simple that no one want to answer ? or :confused:

spud
14th September 2007, 09:15
You can't define the function there, since at that point the compiler doesn't know that QstObjectPrivate inherits PrivateData you have to implement it at the end of the file:


...
class QstObject : public PublicInterface
{
public:
QstObject();
private:
inline QstObjectPrivate* data_pointer_test();
};

class QstObjectPrivate : public PrivateData
{
public:
QstObjectPrivate( PublicInterface *iface )
: PrivateData( iface )
{
}
};

QstObject::QstObject()
: PublicInterface( new QstObjectPrivate(this) )
{
}

QstObjectPrivate* QstObject::data_pointer_test()
{
return static_cast<QstObjectPrivate*>( _data );
}
...

sunil.thaha
14th September 2007, 09:41
Thanks a lot !!
and that helped me make sense of why Qt's pimpl implementation uses reinterpret cast