Shai
Shai

Reputation: 1153

C++: Operator, (comma) doesn't seem to work

I'm writing my class now and testing it. It seems that the comma operator (operator,) refuses to work, the program simply skips it. This is the code I'm running

fileObj << buffer,40;

I wrote the following operators (only prototypes shown, the code isn't relevant):

const file_t& operator<<(const void* buffer);
void operator,(int length);

the "operator<<" works fine, the program uses it but when it arrives to the "operator," , it simply skips it like it doesn't even exist. Needless to say that both operators depend on each other.

Any idea why the comma operator is being skipped? Thanks.

Upvotes: 2

Views: 245

Answers (1)

Rob Kennedy
Rob Kennedy

Reputation: 163257

Your << operator returns a const file_t reference. Your comma operator is a non-const function. Since the types don't match, the compiler does not select your comma operator to perform the operation. Instead, it uses the built-in comma operator, which simply evaluates both operands and returns the right one. (And since evaluation of the right operand has no side effects in your example, it appears as though it's not called at all.)

If your comma operator doesn't modify the object it's called on, then make it const:

void operator,(int length) const;

If the operator needs to modify your object, then don't return a const object from your << operator:

file_t& operator<<(void const* buffer);

Upvotes: 6

Related Questions