Delen via


Simple Assignment (C++)

The simple assignment operator (=) causes the value of the second operand to be stored in the object specified by the first operand. If both objects are of arithmetic types, the right operand is converted to the type of the left, prior to storing the value.

Objects of const and volatile types can be assigned to l-values of types that are just volatile or that are neither const nor volatile.

Assignment to objects of class type (struct, union, and class types) is performed by a function named operator=. The default behavior of this operator function is to perform a bitwise copy; however, this behavior can be modified using overloaded operators. (See Overloaded Operators for more information.)

An object of any unambiguously derived class from a given base class can be assigned to an object of the base class. The reverse is not true because there is an implicit conversion from derived class to base class but not from base class to derived class. For example:

// expre_SimpleAssignment.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class ABase
{
public:
    ABase() { cout << "constructing ABase\n"; }
};

class ADerived : public ABase
{
public:
    ADerived() { cout << "constructing ADerived\n"; }
};

int main()
{
    ABase aBase;
    ADerived aDerived;

    aBase = aDerived; // OK
    aDerived = aBase; // C2679
}

Assignments to reference types behave as if the assignment were being made to the object to which the reference points.

For class-type objects, assignment is different from initialization. To illustrate how different assignment and initialization can be, consider the code

UserType1 A;
UserType2 B = A;

The preceding code shows an initializer; it calls the constructor for UserType2 that takes an argument of type UserType1. Given the code

UserType1 A;
UserType2 B;

B = A;

the assignment statement

B = A; 

can have one of the following effects:

  • Call the function operator= for UserType2, provided operator= is provided with a UserType1 argument.

  • Call the explicit conversion function UserType1::operator UserType2, if such a function exists.

  • Call a constructor UserType2::UserType2, provided such a constructor exists, that takes a UserType1 argument and copies the result.

See Also

Reference

Expressions with Binary Operators