1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - Copy Constructors

By David Bolton, About.com

7 of 10

Using Assignment Operators

An assignment operator is an operator that copies an existing object as in
a = b;
Where a and b are objects of the same class. It is not a constructor but the problems with non POD data are similar. You'll usually find that books on C++ classes refer to assignment operators at the same time as copy constructors. An assignment operator is defined as a non static member function with just one parameter.

Assignment versus Initialization Initialization means creating a new variable and then doing an assignment of a value to it so the only difference is the creation part of initialization. Assignment always works with a variable that exists. If we think in ints then the example below shows examples of assignment, copying and initialization.

int a= 9; // initialization
a =10; // assignment
int b=4; // initialization
a = b; // copying
With objects, the same is true, only assignment and copying can be more complicated if pointers or other non POD objects is involved. BTW, a pointer can be POD if it points to const data or a member function but it's not if new was used.

The assignment operator is another method that the compiler will add for you if you don't supply one yourself. The definition of an assignment operator in class A is

A& operator= (const A& x) throw() ;
In our phonerec example, we might code it like this:
phonerec & operator=(const phonerec & rhs) throw() {
  name= rhs.name;
  phonenumber = rhs.phonenumber;
  return *this;
}
You might wonder why this returns a reference to an object of the same class. It isn't strictly needed - returning void would work ok and you could drop the return *this in that case but it is a convention and it is needed if you ever write multiple assignments like this:
c = b = a;

On the next page An example of assignment Operators

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Using Assignment Operators

©2009 About.com, a part of The New York Times Company.

All rights reserved.