0

I essentially have a cyclic dependency problem where a function uses an object object and the object uses said function. Is there any way to resolve this without working around it?

//function that uses struct
void change_weight(Potato* potato,float byX) { potato->weight+=byX; }
//said struct that uses said function
struct Potato
{
    float weight=0.0;
    Potato(float weightin) { change_weight(weightin); }
};

Note that I understand this example is silly, but this example only contains the "essence of the problem" which has come up in much more complex situations where I would sometimes not know how I would work around it or even if it could be worked around, and it would be very convenient to just be able to do it. I am asking if there is a way to do this without working around it.

  • 2
    You just need to split your declarations and implementations, between the usual .h and .cpp files. – Quentin Apr 26 '16 at 12:59
  • While the code is only an example, it's a pretty bad one... :) The function would fit better as a member function. – Some programmer dude Apr 26 '16 at 13:01
  • @JoachimPileborg In the answer: "Note that I understand this example is silly, but this example only contains the "essence of the problem" which has come up in much more complex situations where I would sometimes not know how I would work around it or even if it could be worked around" – god of llamas May 01 '16 at 15:59

1 Answers1

3

Only declare the constructor in the structure definition, then move the definition out of the structure and place it, together with the function, below the structure definition:

struct Potato
{
    float weight=0.0;
    Potato(float weightin);  // Only declare constructor
}

//function that uses struct
void change_weight(Potato potato,float byX) { potato.weight+=byX; }

// Define the constructor
Potato::Potato(float weightin) { change_weight(*this, weightin); }
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 2
    The question is answered, but note that the code doesn't compile : the call to `change_weight` is missing a parameter. Moreover, `potato` is passed by value. – Quentin Apr 26 '16 at 13:03
  • @Quentin I edited to add a semi-colon at the end and changed the pass by value to pass by reference in both my question and this answer (I tested it on Ideone [here](http://ideone.com/rdCMO5)) – god of llamas May 01 '16 at 15:57