4 Assignments

In both C and C++, we can use the assignment operator on objects. In other words, assuming that X is a named struct, and Y is a class, we can perform the following in C or C++:

struct X a, b;

// ...
a = b;

or, the following only in C++:

class Y c, d;
// ...
c = d;

In both cases, unless the assignment operator is ``overloaded'' in C++, all the compiler does is to generate code to copy the content of b to a, or d to c. In other words,

a = b;

is the same as

memcpy(&a, &b, sizeof(a));

With simple and self-contained structures or classes, this kind of code is sufficient. Even so, however, it raises the question of ``do we really want to copy every data member?''

However, when we have objects that contain pointers to other objects, such a direct method is no longer sufficient. Without introducing data structure topics, let us use the analogy of folders and files.

Let us consider a folder with 300 files. When we want to ``copy'' the folder to a new one, we have two options. The first option is to create a link to the same folder with 300 files. This first method is accomplished by a ``shortcut'' or hard link in WinNT based operating systems, or a ``symlink'' or hard link in Linux. If you are interested in this (off) topic, check out the ln command in Linux.

The second option is to create a new folder, then copy all 300 files over to the newly created folder. This is accomplished by the cp command in Linux, with -r as an option.

The default assignment operator in both C and C++ is equivalent to the use of a symlink or ``shortcut''.

Copyright © 2006-09-05 by Tak Auyeung