Self id of object array

K

Krice

I have a project which has mixed C and C++. Some procedural functions
require an argument which points to the proper array position. The
problem looks something like this:

void My_Class::My_Function()
{
call_procedural(id);
...

ci[id].My_Function();

Is there another way to pass id to call_procedural(id); than

ci[id].My_Function(int id);

Or is this just bad desing I should avoid and write proper member
functions?
 
J

Jonathan Mcdougall

If 'ci' is a container, roll your own, perhaps around std::vector.
Make operator[] return a proxy, remembering the id you passed. Make
that proxy have the same interface as My_Class and forward the calls to
it.

class Proxy
{
private:
int index_;
My_Class &c_;

public:
Proxy(int index, My_Class &c);

void My_Function()
{
c_.My_Function(index_);
}
};

class Container
{
private:
std::vector<MyClass> v_;

public:
Proxy operator[](int index)
{
return Proxy(index, v_[index]);
}
};

Untested, but you should get the picture. And yes, this may be bad
design.

Jonathan
 
K

Krice

Jonathan said:
Untested, but you should get the picture.

Well, I didn't get it:)
And I think, as a temporary solution, passing the id as member function
parameter is the easiest thing to do for now..
 

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
474,202
Messages
2,571,057
Members
47,667
Latest member
DaniloB294

Latest Threads

Top