I am trying to create a progressbar class that can have an arbitrary number of subprogram bars using something similar to a composition pattern.
let's say I have this pbar class:
class pbar { public: pbar(const int w) { width = w; }
As you can see, pbar has two members: width and routines (which themselves are pbars ). I am trying to implement a sync function that changes all the widths of pbars in subbars to match the type of pbar from which it was called:
void pbar::sync() { for ( pbar bar : subbars ) { bar.setwidth(width);
but this does not seem to work. I tried using this test program:
int main() { pbar a(1); pbar b(2); pbar c(3); pbar d(4); c.add(d); b.add(c); a.add(b); a.show(); std::cout << "syncing" << std::endl; a.sync(); a.show(); }
with the show function defined as:
void pbar::show() const { std::cout << w << std::endl; for ( pbar bar : subbars ) { bar.show(); } }
Expected Result:
1 1 1 1
but this:
1 2 3 4
It is strange that the show() function performs the correct iteration to all subclasses, but sync() does not seem to work (in fact, using cout , I confirmed that in fact, but it does not seem to have an effect).
What is wrong with my code? This is not using c++0x for loop, because I tried to use older iterator loops. I cannot find the mistake I made. I think this is due to the fact that I am changing the wrong pbar when using setwidth in sync .
disclaimer: this is actually part of a larger project, and the class is much more complicated than shown here, but I managed to reproduce the undesirable behavior using the above code (which, incidentally, is not copied in brackets and may contain typos)