-1

I need to convert from one struct to another with similar variables. I'm testing this on an example of two structs that have two ints.

For some reason it isn't assigning correctly, I believe that it is sending a local copy that is then deallocated? What am I doing wrong?

Thanks!

#include <iostream>
using namespace std;


struct a
{
    int x, y;

    a(){}

    a(int _x, int _y)
    {
        x = _x;
        y = _y;
    }
};

struct b
{
    int x, y;

    b(){}

    b(int _x, int _y)
    {
        x = _x;
        y = _y;
    }

    b& operator=(const a& _a)
    {
        return b(_a.x, _a.y);
    }
};



int main()
{
    a a_test(1,2);
    b b_test;

    b_test = a_test;

    std::cout << "a: " << a_test.x << "," << a_test.y << endl;
    std::cout << "b: " << b_test.x << "," << b_test.y << endl;
    return 0;
}
user2122589
  • 275
  • 1
  • 5
  • 17

1 Answers1

3
  b& operator=(const a& _a)
  {
      return b(_a.x, _a.y);
  }

You are creating a local copy of b and returning a reference to it. That local copy will be destroyed at the end of the scope.

What you probably wanted to do:

b& operator=(const a& _a)
{
    x = _a.x;
    y = _a.y;
    return *this;
}

The point of assignment operator is to assign a new value to an existing object. It is a member function so it has direct access to the object internals. So you can just change it's members and return a reference to itself to enable further changes.

Edit to address the question in comments how to do the same for class a:

You need to forward declare class b. You will also need to do split the declaration and definition between a header and a source file, because when you will write the definition the compiler needs to know how class b looks like.

In header

class b;

struct a
{
    int x, y;

    a(){}

    a(int _x, int _y)
    {
        x = _x;
        y = _y;
    }

    a& operator=(const b& _b);
};

In cpp

a& a::operator=(const b& _b)
{
    x = _b.x;
    y = _b.y;
    return *this;
}
rozina
  • 4,120
  • 27
  • 49