Ask the C++ Pro 10-Minute Solution

Overloading Operator << for a User-Defined Type
By Danny Kalev

One of the advantages of using the iostream objects is that you can customize them to support your own classes. I will show how to overload ostream's operator << so that it can display a user-defined object.

Suppose you declared the following class:


  class student
  {
  private:
    string name;
    string department;
  public:
    student(string n = "", string dep = 0) 
    : name(n), department(dep) {}

    string get_name() const { return name; }
    string get_department () const { return department; }
    void set_name(const string& n) { name=n; }
    void set_department (const string& d) {department=d;}
  };

And you want to be able to use it in a cout statement as follows:


  student st("Bill Jones", "Zoology"); // create instance
  cout<<st; // display student's details

First, you need to overload the operator << of class ostream (note that cout is an instance of ostream). The canonical form of such an overloaded << is this:


  ostream& operator << (ostream& os, const student& s);

The overloaded << returns a reference to an ostream object and takes two parameters by reference: an ostream object and a user-defined type. The user-defined type is passed as a const parameter because the output operation doesn't modify it. The body of the overloaded << inserts members of the user-defined object into the ostream object:


  os<<s.get_name()<<'\t'<<st.get_department()<<endl;

Make sure that the members inserted are separated by a tab, newline or space so that they appear as if they were concatenated when displayed on the screen. Remember also to place the endl manipulator at the end of the insertion chain to force a buffer flush. Finally, the overloaded operator should return the ostream object after the members have been inserted to it. This will enable you to chain several objects in a single cout statement:


  student s1, s2;
  cout<<s1<<s2;  // chaining multiple objects

The insertion operations and the return statement can be accomplished in a single statement:


  ostream& operator << (ostream& os, const student& s)
  {
    return os<<s.get_name()<<'\t'<<s.get_department()<<endl;
  }

Now you can use the overloaded <<in your code:


   int main()
  {
    student st("Bill Jones", "Zoology");
    cout<<st; 
  }

As expected, this program displays:


  Bill Jones	Zoology
 
Other 10-Minute Solutions
 How to Change the Mouse Pointer without Flicker
 Setting Full Row Selection in ListView Control
 Automating Type Conversions with stringstream Objects
 Improving Memory Reallocation with Vectors
 How to Use <fstream> Classes for File I/O
 Casting About for Safe Typecasting
 Overloading Operator + the Right Way
 How to Create Persistent Objects
 Making Linked Lists More User-Friendly
 Preventing Glitches in Signal Processing
 Forcing Object Allocation on the Free-store
 Using String-Based Data Validation
 Implementing the 'Resource Acquisition Is Initialization' Idiom
 Simple Locks for Data Files
 Template Specializations
 Exception Handling
 Using Bit Fields in Data Optimization
 Using the Transform() Algorithm to Change a String's Case
 Use RTTI for Dynamic Type Identification
 Choosing the Right swap () Implementation
 Take Charge and Initialize Your Own Data
 Share Data Among Objects Using the Monostate Design Pattern
 String Manipulation Made Easy with std::string Algorithms
 Using typedef to Curb Miscreant Code
 Managing Objects' Construction Order
 Bitwise Operators: Combining Efficiency and Ease of Use
 Use Function Adapters to Extend Generic Algorithms' Usage
 Simplify Callback Dispatching with Enumerated Indexes
 Streamline Your Bulk I/O Operations with Stream Iterators
 Optimize Your Member Layout
 Preserve Code Safety with Conversion Operators
 Modify Your Base Class Interface in Derived Classes
 Tackle Common Programming Tasks Using the New <tuple> Library
 Use Local Classes for Proper Cleanup in Exception-enabled Apps
 Use multimap to Create Associative Containers with Duplicate Keys
 Enforcing Compile-time Constraints
 Facilitate Directory Operations with the <dirent.h> and <dir.h> Libraries
 Spruce Up Your Built-in Arrays
 Target 32- and 64-bit Platforms Together with a Few Simple Datatype Changes
 Restrict Object Allocation to Specific Memory Types
 Use the Pimpl Idiom to Reduce Compilation Time and Enhance Encapsulation
 Automate Resource Management with shared_ptr
 The Quick and Dirty Way to Add
 Pointing to Class Members
 Detecting Keystrokes While Your Application is Busy
 Linked Lists
 Programming the System Tray
 Create a "Universal" DLL
 Convert Path to Long Path Name
 Constructing an Object at a Pre-Determined Memory Position
 Declaring Classes and Member Functions in a Namespace
 Using the auto_ptr Class Template to Facilitate Dynamic Memory Management
 Using the random_shuffle() Algorithm to Randomize a Sequence of Elements
 Defining a Function Object
 Implementing the Singleton Design Pattern
 Declaring Function Pointers and Implementing Callbacks
 Overloading Operator << for a User-Defined Type
 Implementing a Stopwatch Class for Performance Measurements
 Creating and Accessing Environment Variables
 Executing an Object's Member Function in a Separate Thread
 Creating Heterogeneous Containers
 Overriding New and Delete
 Time and Date Manipulation
  Defining Functions with a Variable Argument List
 Optimize Abstract Operations with Function Templates




Sponsored Links


Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map
Jupiterweb networks

internet.comearthweb.comDevx.comClickZ

Search Jupiterweb:

Jupitermedia Corporation has four divisions:
JupiterWeb, JupiterResearch, JupiterEvents, and JupiterImages

Copyright 2004 Jupitermedia Corporation All Rights Reserved.
Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Jupitermedia Corporate Info | Newsletters | Tech Jobs | E-mail Offers