How, exactly, are chained assignments processed?

  • Thread starter Thread starter in the rye
  • Start date Start date
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 1K views
in the rye
Messages
83
Reaction score
6
Hi all,

I have a question. I am writing a copy constructor for a class, and I'm not sure this has ever made sense to me. When we write the copy constructor we return *this to support chained assignments. But my question is, why is this required?

Suppose we have integers a,b,c where c = 0. If I assign:
a = b = c I understand that b = c will assign 0 to b then return 0 so that a is assigned 0. However, why is the return value in the constructor required? It seems to me that if we left it out, b=c should be assigned, return nothing, but does this means that the b=c just drops out from the expression entirely so that we have nothing on the rhs?

It just seems like a should be assigned 0 regardless. Since b=c will be assigned 0 and now a is being assigned to b and b is now 0. The return value doesn't seem to be necessary, but obviously I'm wrong and I want to know why.

Thanks.
 
Physics news on Phys.org
in the rye said:
Hi all,

I have a question. I am writing a copy constructor for a class, and I'm not sure this has ever made sense to me. When we write the copy constructor we return *this to support chained assignments. But my question is, why is this required?

Suppose we have integers a,b,c where c = 0. If I assign:
a = b = c I understand that b = c will assign 0 to b then return 0 so that a is assigned 0. However, why is the return value in the constructor required? It seems to me that if we left it out, b=c should be assigned, return nothing, but does this means that the b=c just drops out from the expression entirely so that we have nothing on the rhs?

It just seems like a should be assigned 0 regardless. Since b=c will be assigned 0 and now a is being assigned to b and b is now 0. The return value doesn't seem to be necessary, but obviously I'm wrong and I want to know why.

Thanks.
How about this:
C:
float a, c;
int b;

a = b = c = 1.3f;
 
First off, be careful with terminology.

The copy constructor does not return anything. You are talking about an assignment operator and they are different.

Code:
struct foo {
   foo(const foo& other) x(other.x){}  //This is the copy constructor
   foo & operator = (const foo & other){ x = other.x;  return *this; }  //This is an assignment operator
};
We also occasionally use the results of assignments to check the value within to know whether to do into another scope.
Code:
if (FILE * fp = fopen("/tmp/somefile", "a")){
   fwrite(fp, 1,1, "a");
} else {
   std::cerr << "Could not open file" << std::endl;
}