Private interface using reinterpret_cast vs. inheritance (long)

N

news_mail_jpa

Hi!

I'd like to implement a private interface and I have the choices
mentioned in the subject. The implementation using private inheritance
is probably cleaner but it also adds some space and time overhead
compared to the 'cast' -method. The problem with the cast method is
that I don't know whether its C++ standard-compliant and/or portable?

Example:

// Inheritance method
class LayerData {
public:
virtual int usefullStuffToLayer() = 0;
virtual Object* getObjectInterface() = 0;
};

class Layer {
public:
void doSomething(LayerData* p)
{
int stuff = p->usefullStuffToLayer();
// needs the Object -interface e.g. in callbacks
xyz->result(p->getObjectInterface());
};
};

class Object : private LayerData {
public:
void clientMethod() { pNext_->doSomething(this); };

private:
virtual int usefullStuffToLayer() { return 1; };
virtual Object* getObjectInterface() { return this; };

Layer* pNext_;
};

Object offers an interface to its clients but wants to hide the
LayerData part. That private interface is passed along when forwarding
calls to the Layer. However, for some reason the Layer also needs the
Object -interface, hence the conversion method. This is okay but it
adds some space (vtbl) and time overhead (v-methods) so I started to
think something like:

class LayerData {
public:
int usefullStuffToLayer() { return 1; };
Object* getObjectInterface()
{ return reinterpret_cast<Object*>(this) };
private:
friend class Object;

// all Object data items here
Layer* pNext_;
};

// Layer stays the same

class Object {
public:
void clientMethod() { data_.pNext_->doSomething(&data_); };

private:
// this will be the only data-item
LayerData data_;
};

So, is this portable and/or standard-compliant? Of course I could add a
parent-pointer to the LayerData-object but I wouldn't like to unless
forced to do so (that would effectively reserve the space spared from
the not_needed vtbl-pointer). Object doesn't inherit anything and
nobody is going to inherit from it.

BR, jpa
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top