Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

15.5. Writing an Operator That Isn’t a Member Function

Problem

You have to write a binary operator, and you can’t or don’t want to make it a class member function.

Solution

Use the operator keyword, a temporary variable, and a copy constructor to do most of the work, and return the temporary object. Example 15-5 presents a simple string concatenation operator for a custom String class.

Example 15-5. Concatenation with a nonmember operator

#include <iostream>
#include <cstring>

class String {  // Assume the String class declaration
                // has at least everything shown here
public:
   String();
   String(const char* p);
   String(const String& orig);
  ~String() {delete buf_;}

   String& append(const String& s);
   size_t length() const;
   const char* data() const;
   String& operator=(const String& orig);

   // ...
};

String operator+(const String& lhs, const String& rhs) {

   String tmp(lhs); // Copy construct a temp object
   tmp.append(rhs); // Use a member function to do the real work

   return(tmp);     // Return the temporary
}

int main() {

   String s1("banana ");
   String s2("rancher");
   String s3, s4, s5, s6;

   s3 = s1 + s2;           // Works fine, no surprises
   s4 = s1 + "rama";       // Constructs "rama" automatically using
                           // the constructor String(const char*)
   s5 = "ham " + s2;       // Hey cool, it even does it backward
   s6 = s1 + "rama " + s2;

   std::cout << "s3 = " << s3.data() << '\n';
   std::cout << "s4 = " << s4.data() << '\n';
   std::cout << "s5 = " << s5.data() << '\n';
   std::cout << "s6 = " << s6.data() << '\n';
}

Discussion

A standalone operator ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page