-1

I'm currently working on a C++ assignment and I have 3 different types of objects. Customer, Hire and Tour. When I create a object now I do the following, I read the data from a file and then do the following,

Customer* cust = new Customer(custId, Name, ...);

However the requirement is to use >> operators to read this information into objects. Also use << write it back. How can I achieve this?

Many thanks :)

David G
  • 94,763
  • 41
  • 167
  • 253
Achintha Gunasekara
  • 1,165
  • 1
  • 15
  • 29
  • 4
    Step 1: You **don't** want to _override_ `operator<<()` or `operator>>()`. In fact, you can't! You _can_, however, _overload_ these operators. It may be a small difference in words but it is semantically a major difference. – Dietmar Kühl Oct 14 '13 at 22:01
  • Related: http://stackoverflow.com/q/4421706/332733 – Mgetz Oct 14 '13 at 22:03

2 Answers2

4

First of all, there is likely no need for your to create objects on the heap.

After you've made those corrections, you can overload the insertion and extraction operators:

// assuming you declare these operators as friends of Customer
std::ostream& operator<<(std::ostream& os, const Customer& c)
{
    os << c.data;
    return os;
}

std::istream& operator>>(std::istream& is, Customer& c)
{
    is >> c.data;
    return is;
}
Zac Howland
  • 15,777
  • 1
  • 26
  • 42
1

Well here is a really good reference (apparently not that good because I had to fix some of the code) for overloading the io operators. I can't tell you much more with out knowing the details of your class, however I can say that the beauty of the stream operators is that they provide an interface to any stream type object not just stdin and stdout. Here is a little example from the site:
#include using namespace std; class Point { private: double m_dX, m_dY, m_dZ;

public:
    Point(double dX=0.0, double dY=0.0, double dZ=0.0)
    {
    m_dX = dX;
    m_dY = dY;
    m_dZ = dZ;
    }

    friend ostream& operator<< (ostream &out, Point &cPoint);
    friend istream& operator>> (istream &in, Point &cPoint);     
    double GetX() { return m_dX; }
    double GetY() { return m_dY; }
    double GetZ() { return m_dZ; }
};

ostream& operator<< (ostream &out, Point &cPoint)
{
    // Since operator<< is a friend of the Point class, we can access
    // Point's members directly.
    out << cPoint.m_dX << " " << cPoint.m_dY << " " << cPoint.m_dZ << std::endl;
    return out;
}

istream& operator>> (istream &in, Point &cPoint)
{
    in >> cPoint.m_dX;
    in >> cPoint.m_dY;
    in >> cPoint.m_dZ;
    return in;
}  

IMO the best way to think about overloading these operators is to leverage previously written >> and << and that way you sort of build a chain and it becomes extremely simple and convenient to implement these operators.

aaronman
  • 18,343
  • 7
  • 63
  • 78