Multiple insertion operator << in C++

1.3k views Asked by At

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.

1

There are 1 answers

0
πάντα ῥεῖ On BEST ANSWER

You probably meant to write some code like follows

#include <iostream>
using namespace std;

class MyClass {
    public:
        int i;
        MyClass & operator<< ( const string &  );
} ;

MyClass& MyClass::operator<< ( const string & str) { // Note the parameter symbol
    cout << str << endl ; // Note usage of the parameter symbol "str", "this" is not 
                          // what you actually want here, it just outputs the address 
                          // of the class instance
    return *this; // Return the instance reference properly to allow chaining of
                  // subsequent operator<<() calls
}

int main() {
    MyClass mc;

    mc << "hello" << "world" ;
}

Output

hello
world

See LIVE DEMO


Let's break this down:

 mc << "hello" << "world";

actually is the same as calling

 mc << "hello";
 mc << "world";

Returning the instance reference will enable the function being called in a chain of operator calls applied.


"But in reality, it seems a "temporary" MyClass between the operations."

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 the operator<<(). The compiler should have at least issued a warning about the missing return statement.