tags:

views:

89

answers:

3

Possible Duplicate:
Why does C++ support memberwise assignment of arrays within structs, but not generally?

Why is it that we can assign the object of one structure to other directly eg:

struct student s1,s2;
s2=s1 //is perfectly ok.

but we can not assign one array value to the other eg:

int a[10],b[10];
a=b //is not allowed.

though the element of structure may contain any no of arrays.

Please Explain.

A: 

This is how it is specified to be. If you need assignable arrays, use std::vector:

std::vector< int> a(10), b(10);
a = b;

The rule for default assignment operator for structs (and classes) is that it calls the assignment operators for base structs/classes and then the assignment operators for each data member.

Cătălin Pitiș
If assignment operator for each data member is applied, how is it arrays inside structs are copied? I think it's copied byte per byte, right?
Gunner
Maybe, maybe not. If you have an array like MyComplicatedType[], then the array will be copied by invoking the MyComplicatedType copy constructor once for each array element.
David Seiler
Yes, bitwise copy, AFAIK.
Cătălin Pitiș
I dont need a solution for vector... my question is why it doesnt happen in case of arrays??
Xaero
If you need an "assignable array," you should use a `std::array` (or `std::tr1::array` or `boost::array`). A `std::vector` is not always appropriate, especially if you need an array with a small number of elements and the number is known at compile time.
James McNellis
BTW is bit-wise or byte-wise? Can anyone confirm?
Xaero
+2  A: 

Array assignment is not allowed at language level for purely historical reasons. Check also this question.

Kirill V. Lyadvinsky
+1  A: 

Ultimately, I don't think there is a reason that has much in the way of theoretical basis. I'd guess that it comes down to an expectation that arrays are typically large enough that preventing accidental copying was worthwhile.

By contrast, I think the expectation was that structs would typically be small enough that the convenience of supporting assignment outweighed the risk of possibly doing something unexpectedly expensive.

Jerry Coffin
It can happen in case of structs as well which might contain a very large array?
Xaero
Jerry Coffin