I write a small code to see what happen if I use series insertion operators to own class.
#include <iostream>
using namespace std;
class MyClass
{
public:
int i;
MyClass & operator<< ( const string & );
} ;
MyClass& MyClass::operator<< ( const string & )
{
cout << this << endl ;
}
int main()
{
MyClass mc;
mc << "hello" << "world" ;
}
It gives the result of two different memory addresses, which is beyond my imagination.
0x7fffdc69f6df
0x6020a0
I though it should be like:
(( mc << "hello" ) << "world" );
But in reality, it seems a "temporary" MyClass between the operations. This causes the member variable (for example, int i
in the class) will not consistent. Can anyone give comments about this if I want the member variable (int i
) can be access consistently.
You probably meant to write some code like follows
Output
See LIVE DEMO
Let's break this down:
actually is the same as calling
Returning the instance reference will enable the function being called in a chain of operator calls applied.
The problem occurs that you've been missing to return the current instance using the
return *this;
statement. Thus the accessing the expected return value results in undefined behavior for the 2nd call of theoperator<<()
. The compiler should have at least issued a warning about the missingreturn
statement.