Search code examples
c++structassign

Are there potential issues with assigning structures to one another?


If I just have a simple structure such as the following, where the types of member variables can be ANY built-in type or classes previously created:

using TypeA = ..sometype1;
using TypeB = ..sometype2;

struct Relation{
    TypeA A;
    TypeB B;
};

int main(){
    Relation x;
    Relation y;
    ...some code doing stuff to x and y..
    x=y;
    ...some more code...
}

Will this always compile and do the intended task, meaning there is only one possible task it can do, which is assiging to x the exact data in y? Are there cases where I must be careful with such assignments?


Solution

  • Objects of struct or class type are not special, basically the same caveats exist as for other types. Which problems may or may not apply depends on the members, because the default assignment operation operation does a memberwise assignment. If you need different behaviour, you can always customize this by providing your own assignment operator.