Mariska
Mariska

Reputation: 1949

Initializing a class in another function

I have a code that if simplified would look like this:

void foo(MyObject& y){
    int 2;
    MyObject y(2);
}

int main (int argc, char** argv) {
    MyObject x;
    foo(x);
    x.run();
}

However, I get the error message "error: declaration of 'MyObject y' shadows a parameter. Note that foo() is originally a much more complicated function, i.e., I would rather not copy and paste foo's code to main (although it looks very possible in the above example). What I would like to do here is that to pass MyObject x to foo in main(), initialize x in foo(), and call x.run() in main.

Any ideas?

Upvotes: 0

Views: 61

Answers (2)

Clifford
Clifford

Reputation: 93544

Your definition of foo() does not do what you think, it has a parameter called y and a local variable also called y; they do not refer to the same object.

void foo(MyObject& y){
    int 2;
    MyObject y(2);  // This is a new instance of MyObject independent of the parameter y
}

Solutions include:

  • Adding a "modifier" method to MyObject to change its state y.set(2),
  • Constructing a temporary MyObject and assigning it to y: y = MyObject(2),
  • Returning a copy of a temporary object: return MyObject(2) (making the reference parameter unnecessary).

These last two require that your class has suitable copy semantics, which may require a copy constructor or assignment operator to be defined if the object is not trivial.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227468

You can't initialize an object twice. What you can do is assign it a different value:

void foo(MyObject& y){
    int n = 2;
    y = MyObject(n);
}

Alternatively, write a function that initialized an object and returns it:

MyObject foo(){
    int n = 2;
    return MyObject(n);
}

MyObject m(foo());

Upvotes: 5

Related Questions