Detheroc
Detheroc

Reputation: 1921

How to change the return value of operator=?

So i have been creating this "framework" thing that basically puts together source code (for shaders). I thought i was pretty clever when i came up with the idea of making a statement class and overloading all of its operators (changing their meaning completely) to form other statements in a natural way. It looks like this:

class Statement {

public:
    Statement operator=(const Statement &other) const;
    Statement operator+(const Statement &other) const;
    ...

}

However, when i thought i was done, it turned out that the operator= completely disregarded the return value and instead just always returned the object before the '='. Do i understand it correctly that there is no way to accomplish this?

EDIT: Ok, sorry, the example i provided compiles (i had the operator overloaded in A too which didn't work).

EDIT 2: The operator= is actually const on purpose: Its intended meaning is to create a new assignment statement object.

Example:

Block b; // Represents a sequence of commands.
Statement var1, var2; // Represent some variables.
...
b.append(var1 = var2);

Expected: b includes the command var1 = var2;

Observed: b includes var1;

Resolved: The problem was because i was using a derived class instead of Statement which used its default operator=. Thanks everyone.

Upvotes: 0

Views: 157

Answers (2)

Jonathan Wakely
Jonathan Wakely

Reputation: 171403

Unless you declare one, a class always has an implicitly-declared copy-assignment operator with the signature:

Statement& operator=(const Statement&)

Note it is not const, so is preferred when assigning to a non-const object, because your assignment operator is const. [Edit: my mistake, the const assignment operator suppresses the implicit one, so the unconventional const-qualified assignment operator should be used.]

(how do you expect to assign to I.e. modify, a const object?)

(N.B. to be more accurate, the implicitly-declared assignment operator could have the signature Statement& operator=(Signature&) if a sub-object declares an assignment operator with that signature, but that's not the case in your example.)

Upvotes: 4

Mankarse
Mankarse

Reputation: 40633

Your code is fine (and it works with g++-4.5.1, g++-4.3.4, Clang and VS2010). If it does not work then there must either be something wrong with your compiler, or there must be something that you are not telling us.

Upvotes: 1

Related Questions