dynamic class members workaround

S

Shailesh

If I'm not mistaken, C++ doesn't have support for dynamic class
members. I'm considering if such a facility would be useful, and what
method would make a good workaround.

I have a generic buffer class, which can have one or more cursor
classes attached to it. Right now, they are both separate classes,
and I use them as follows:

class Buffer {
...
}
class Cursor {
...
}

pBuffer = new Buffer;
pCursor = pBuffer->CreateCursor();
pCursor->Insert();
....
pBuffer->DestroyCursor(pCursor);

The parent buffer of pCursor is implicit at the Insert() call, when it
would preferably be explicit. A cleaner facility might be to create a
dynamic member for each cursor. Below, the parameter to CreateCursor
is the new name of the dynamic member, and the function knows the type
to which it must be initialized. The syntax
"pBuffer->pCursor->Insert()" would trigger an overridable lookup and
dispatch function in the buffer class, followed by the Insert()
function of the particular cursor instance.

pBuffer = new Buffer;
pBuffer->CreateCursor("pCursor");
pBuffer->pCursor->Insert();
....
pBuffer->DestroyCursor("pCursor");

The only way I can think of to achieve this kind of behavior, short of
importing some specialized non-standard library, is to use handles, C
style. Statement (2) below was actually my original technique, but
then the cursor and buffer code was intermingled.

pBuffer = new Buffer;
HANDLE pCursor;
pCursor = pBuffer->CreateCursor();
(1) pBuffer->GetCursor(pCursor)->Insert();
-OR-
(2) pBuffer->Insert(pCursor);
....
pBuffer->DestroyCursor(pCursor);

The drawback of the handle technique is that handles must be
maintained outside of the class, but it is fast because the handles
can be the indexes into the cursor class instance pointers array. I
suppose I could create a hash table for cursor names, and then refer
to them using the string name, like this:

pBuffer = new Buffer;
pBuffer->CreateCursor("MyCursor");
pBuffer->GetCursor("MyCursor")->Insert();
....
pBuffer->DestroyCursor("MyCursor");

I like this solution, but there is performance overhead of using a
hash table to lookup the class instance for the given string at
runtime. Anyway, I'm just writing to clarify my thoughts. I will
probably use the split class method I outlined first just for its low
overhead. If you have any comments, feel free to reply.
 

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

Forum statistics

Threads
474,167
Messages
2,570,910
Members
47,453
Latest member
MadelinePh

Latest Threads

Top