12

Suppose I have a structure in C++ containing a name and a number, e.g.

struct person {

char name[20];

int ssn;

};

Suppose I declare two person variables:

person a;

person b;

where a.name = "George", a.ssn = 1, and b.name = "Fred" and b.ssn = 2.

Suppose later in the code

a = b;

printf("%s %d\n",a.name, a.ssn);
rohitt
  • 1,124
  • 6
  • 18
skydoor
  • 25,218
  • 52
  • 147
  • 201
  • 10
    Is there a question somewhere in there? – Turtle Mar 20 '10 at 17:43
  • 1
    Skydoor appears to believe that SO is a replacement for reading books, or even thinking. 129 questions - zero answers. –  Mar 20 '10 at 17:53
  • Speaking of books, may I point you to http://www.amazon.com/Primer-Plus-5th-Stephen-Prata/dp/0672326973/ref=sr_1_1?ie=UTF8&s=books&qid=1269107822&sr=8-1 – wheaties Mar 20 '10 at 17:57
  • @wheaties Why would you want to do that? Why not point them at something useful, such as http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list –  Mar 20 '10 at 17:58

2 Answers2

27

The default assignment operator does a member-wise recursive assignment of each member.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
10

The default assignment operator in C++ uses Memberwise Assignment to copy the values. That is it effectively assigns all members to each other. In this case that would cause b to have the same values as a.

For example

a = b;
printf("%s\n", b.name); // Prints: George
b.name[0]='T';
printf("%s\n", a.Name); // Prints George
printf("%s\n", b.name); // Prints Teorge
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454