Thread: Reading a class object with cin.

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    76

    Reading a class object with cin.

    I have used member variables and operated on them with the help of member functions. Bu in one of the examples in C++ Primmer i found something like this:

    Code:
    Sales_item book;               \\book is an object of class Sales_item
    cin>>book;
    cout<<book;
    How is it possible to read the object and output that after processing without using '.' operator and any member variable/function? I tried looking into the header "Sales_item.h" but didn't understand that.

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    You'll need to overload the >> operator for your class type. Something like this:
    Code:
    std::istream& operator>>(std::istream& is, Sales_item& item)
    {
      is >> item.some_field;
      is >> item.some_other_field;
    
      return is;
    }
    And then do something similar with the << operator and std::ostream.

    Of course this is a very oversimplified example. You need to check for errors at every step of the way.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    operator overloading - cppreference.com
    Scroll down to "Stream extraction and insertion"
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading a class object from ASCII file...
    By ManyTimes in forum C++ Programming
    Replies: 2
    Last Post: 03-20-2010, 08:09 PM
  2. Reading a class object from a file...
    By ManyTimes in forum C++ Programming
    Replies: 2
    Last Post: 03-18-2010, 07:22 PM
  3. Replies: 10
    Last Post: 05-22-2009, 11:12 PM
  4. pointer to struct object in class object
    By Stevo in forum C++ Programming
    Replies: 3
    Last Post: 02-25-2004, 07:58 PM
  5. Replies: 3
    Last Post: 02-12-2002, 10:09 PM

Tags for this Thread