You are here:

C++/overloading << and >> operators

Advertisement


Question

Hello, Vijayan

I know that in order to overload the << and >> operators I must do sth like this inside my class:

friend ostream operator<<(ostream& out, const ClassType&);
friend istream operator>>(istream& in, ClassType&);

I've been able to use this in my programs, but I dont understand how this works inside the compiler.
What I mean is, how and when do the 2 args get sent to the functions??

So in my main prog, i would have sth like this

cout<<object;
cin>>object;

how does the compiler interpret this??

Thanks

Answer
the overloaded << operator is used by the compiler this way.
note: C++ streams are not copyable; you must return references.

with:
ostream& operator<<(ostream& out, const ClassType&);
istream& operator>>(istream& in, ClassType&);

void foo( ostream& out, istream& in, ClassType& object )
{
    out << object ; // is interpreted as the next statement
    operator<< ( out, object ) ;

    in >> object ; // is interpreted as the next statement
    operator>> ( in, object ) ;
}

in general, if @ is a placeholder for a binary operator overloaded via a free function,
    a @ b ;
is evaluated by the compiler as:
    operator@ ( a, b ) ;

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.