Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assigning one struct variable to the another varible of a same type which is in different struct in C++

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
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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};
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading