1

Can we assign one variable from a structure to another variable of a same type which is in a different struct, directly in C++? Such as:

struct Test1 
{
   inx x1;
   int y1;
}

struct Test2
{
   int x2;
   int y2;
}

void trialStruct(Test2& origin2)
{
   Test1 origin1;
   origin1.x1 = origin2.x2;
   origin2.y1 = origin2.y2
}
  • 4
    Yes, you can. Is there anything that makes you think you couldn't? – Lukas-T Sep 02 '22 at 08:16
  • 2
    BTW: You really want to make a copy by passing the struct? So you should use a reference. And naming your function try looks mysterious as try is a keyword in c++. Why you did not check your code with a debugger? – Klaus Sep 02 '22 at 08:18
  • With the exception that you can't name a function `try` (and the typo in `inx`) it's all fine and well. – Some programmer dude Sep 02 '22 at 08:19
  • This is explained in any beginner [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Sep 02 '22 at 08:20
  • 1
    As mentioned before: yes. You can do this, but this isn't the most efficient way of doing it. You could just as easily create an overloaded constructor for Test1 like `Test1(const Test2& org): x1(org.x2), y1(org.y2) {}` – SimonC Sep 02 '22 at 08:20
  • @churil Someone said that this wouldn't work without casting because struct types are different. That's why I wanted to be sure – Günkut Ağabeyoğlu Sep 02 '22 at 08:22
  • 1
    Change your try function to `void try_it(Test2& origin2)` and try your self. – Victor Gubin Sep 02 '22 at 08:22
  • 1
    @GünkutAğabeyoğlu Casting these structs to one another is theoretically possible, because they have the same data structure. It'd be easy enough to just `memcpy` them over one another – SimonC Sep 02 '22 at 08:25
  • 2
    Casting and memcpy to data of different structs should be avoided at all. If it is the same type, you can directly assign if it is not the same type, don't cast nor memcpy even if the layout is the self. Latest in the moment during program maintenance of a prog this will be a hard to find bug. BTW: it is UB – Klaus Sep 02 '22 at 08:28

1 Answers1

3

Can we assign one variable from a structure to another variable of a same type which is in a different struct, directly in C++?

Yes, the type of origin1.x1 and origin2.x2 is same(both are int) and we can assign origin2.x2 to origin1.x1 as you've done in your example.


Note also that instead of assigning individual members, you can use aggregate initialization to initialize the data member in your particular example as shown below:

void trialStruct(Test2& origin2)
{
   //aggregate initialization 
   Test1 origin1{origin2.x2, origin2.y2};
}
Jason
  • 36,170
  • 5
  • 26
  • 60