Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ default assignment operator

int a[10];
int b[10];
a = b;

//

struct test {
    int a[10];
};

test a,b;
a = b;

First code doesn't compile, since we cant assign array, but the second does. Isn't the default assignment operator of class simply call assignment for each data members? Why does the the second code compile?

like image 691
Ashot Avatar asked Aug 08 '13 06:08

Ashot


People also ask

Is it a == assignment operator?

The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.

Does C have assignment operators?

Assignment Operators in C/C++ Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value.

Is assignment operator present by default in a class?

The answer is same as Copy Constructor. If a class doesn't contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class.


1 Answers

From the C++11 draft, section 12.8:

The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy/move assignment of its subobjects. The direct base classes of X are assigned first, in the order of their declaration in the base-specifier-list, and then the immediate non-static data members of X are assigned, in the order in which they were declared in the class definition. Let x be either the parameter of the function or, for the move operator, an xvalue referring to the parameter. Each subobject is assigned in the manner appropriate to its type:

— if the subobject is of class type, as if by a call to operator= with the subobject as the object expression and the corresponding subobject of x as a single function argument (as if by explicit qualification; that is, ignoring any possible virtual overriding functions in more derived classes);

— if the subobject is an array, each element is assigned, in the manner appropriate to the element type;

— if the subobject is of scalar type, the built-in assignment operator is used.

The important part here is: if the subobject is an array, each element is assigned, in the manner appropriate to the element type;

like image 181
Borgleader Avatar answered Sep 23 '22 16:09

Borgleader