Search code examples
c++pointersoperator-overloadingistreamostream

istream >> ostream << Operator Overloading with * Pointer


How would I overload the >> and << operators if they are dealing with pointers?

in header:

friend std::istream& operator >>( std::istream& ins, Classname* & e);
friend std::ostream& operator <<( std::ostream& outs, const Classname * e);

in cpp:

std::ostream& operator <<( std::ostream& outs, const Classname * e)
{   // what do I do here?
return outs;
}
std::istream& operator >>( std::istream& ins, Classname* & e){
// what do I do here?
    return ins;
}

Solution

  • It depends on what is in the class Classname. If for example you have:

    class Classname {
    //...
    private:
      int a;
    };
    

    .. then you might do:

    std::ostream& operator <<( std::ostream& outs, const Classname * e)
    {  
      outs << e->a;
      return outs;
    }
    std::istream& operator >>( std::istream& ins, Classname* & e){
        ins >> e->a;
        return ins;
    }
    

    The idea being that the << and >> operators ideally should mirror each other - so for example you can make use of them for serializing and deserializing your instances.