Skip to content

Latest commit

 

History

History
86 lines (70 loc) · 2.15 KB

File metadata and controls

86 lines (70 loc) · 2.15 KB
title Assignment | Microsoft Docs
ms.custom
ms.date 11/04/2016
ms.reviewer
ms.suite
ms.technology
devlang-cpp
ms.tgt_pltfrm
ms.topic language-reference
dev_langs
C++
helpviewer_keywords
operators [C++], assignment
assignment operators, overloaded
ms.assetid d87e4f89-f8f5-42c1-9d3c-184bca9d0e15
caps.latest.revision 7
author mikeblome
ms.author mblome
manager ghogen
translation.priority.ht
cs-cz
de-de
es-es
fr-fr
it-it
ja-jp
ko-kr
pl-pl
pt-br
ru-ru
tr-tr
zh-cn
zh-tw
translationtype Human Translation
ms.sourcegitcommit 3168772cbb7e8127523bc2fc2da5cc9b4f59beb8
ms.openlocfilehash 9142209d1f7e2f9c80a5e2ec7dd282d47e4f0899

Assignment

The assignment operator (=) is, strictly speaking, a binary operator. Its declaration is identical to any other binary operator, with the following exceptions:

  • It must be a nonstatic member function. No operator= can be declared as a nonmember function.

  • It is not inherited by derived classes.

  • A default operator= function can be generated by the compiler for class types if none exists. (For more information about default operator= functions, see Memberwise Assignment and Initialization.)

The following example illustrates how to declare an assignment operator:

// assignment.cpp  
class Point  
{  
public:  
   Point &operator=( Point & );  // Right side is the argument.  
   int _x, _y;  
};  
  
// Define assignment operator.  
Point &Point::operator=( Point &ptRHS )  
{  
   _x = ptRHS._x;  
   _y = ptRHS._y;  
  
   return *this;  // Assignment operator returns left side.  
}  
  
int main()  
{  
}  

Note that the supplied argument is the right side of the expression. The operator returns the object to preserve the behavior of the assignment operator, which returns the value of the left side after the assignment is complete. This allows writing statements such as:

pt1 = pt2 = pt3;  

See Also

Operator Overloading