Click Here!
home account info subscribe login search My ITKnowledge FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

C++ in Plain English
(Publisher: IDG Books Worldwide, Inc.)
Author(s): Brian Overland
ISBN: 1558284729
Publication Date: 04/01/96

Bookmark It

Search this book:
 
Previous Table of Contents Next


Chapter 7
Class Operations (Operator Overloading)

Operator overloading enables you to define the meaning of operators such as +, -, *, and / when applied to your class. There are few C++ operators you cannot define for your class, a fact that makes C++ perhaps more flexible than any other programming language you’ve ever seen.

In general, overloading is the reuse of a name or a symbol in a new context. For example, the compiler handles integer addition and floating-point addition differently, although you may not be aware of it. With the CStr class, addition should mean something different from both integer and floating-point addition. This chapter will define CStr addition to mean concatenation of strings.

With C++, you write operator functions to define how each operator works. If you don’t write an addition operator function for the class, attempting to use the plus sign (+) with objects of the class results in an error.

The Basic Syntax

There are a number of subtle twists and turns when it comes to operator functions, but the basic syntax is simple. For a given operator @, the name of the operator function is:

operator@

So, for example, operator functions for +, -, *, and / have the following names:

operator+
operator-
operator*
operator/

This looks deceptively simple, and you probably suspect that there’s more to this operator business. To begin with, what are the arguments? The answer depends on a couple of factors:

  Is the operation binary or unary? (Note that some operators, such as the minus sign, can go both ways.)
  If the operation is binary, do you want to support the occurrence of objects on either side of the operator? For example, do you want to support both string + cstr_object and cstr_object + string? If you do, you need to use friend functions. (These global functions are given access to the class through use of the friend keyword.)

It’s beginning to get more complicated, but this chapter will explain esoteric concepts such as friend functions. In any case, here is the proper syntax for the addition functions:

class CStr {
...
   CStr friend operator+(CStr str1, CStr str2);
   CStr friend operator+(CStr str, char *s);
   CStr friend operator+(char *s, CStr str);
};

CStr operator+(CStr str1, CStr str2) {
...
}

CStr operator+(CStr str, Char *s) {
...
}

CStr operator+(char *s, CStr str) {
...
}

You should be able to see a strong connection between function overloading and operator overloading here. There can be many functions named operator+. What differentiates these functions is their argument lists. The operator+ functions that have one or more CStr arguments are the ones that define how addition works with CStr objects.

Writing the Addition (+) Operator Function

The following definition successfully implements the addition of two CStr objects. Each of the arguments represents an operand in the expression str1+str2.

CStr operator+(CStr str1, CStr str2) {
   CStr new_string(str1);
   new_string.cat(str2.get());
   return new_string;
}

CStr appears at the beginning of the function heading as the return-value type. To return a CStr result, the operator+ function definition creates an entirely new CStr object in the first line:

    CStr new_string(str1);

This statement calls the copy constructor to initialize new_string as an exact copy of str1, the first operand. The next statement concatenates the second operand, str2, onto the end of new_string. This process produces the very string we wanted to build.

    new_string.cat(str2.get());

The final task is to pass the new string as the return value.

    return new_string;

This statement makes a copy of new_string before it goes out of scope and is destroyed. As explained in Chapter 6, the compiler automatically invokes the copy constructor, CStr(CStr&), to create the return-value copy. This same return-value object is placed on the stack, where the caller can access it.

With a sophisticated class such as CStr, returning a value would fail without a correctly written copy constructor. The hidden copy constructor supplied by the compiler would perform a straight member-by-member copy that would result in errors. That’s why I introduced the subject of copy construction first (in Chapter 6) before describing how operator overloading works.

The Mechanics of Calling an Operator Function

When C++ sees an expression such as str1 + str2, it translates the expression into the appropriate function call. Figure 7.1 illustrates how this works. If the function call did not exist, it would report an error at compile time saying that the operation was not defined.


Figure 7.1  Translation of an expression.

The following code shows an example of how string addition might be used. Each of the following statements is an object definition. The last uses statement carries out an addition operation (calling the operator+ function) to produce a CStr value. That value is then used to initialize the object name by means of the copy constructor.

CStr first(“Archie ”);
CStr last(“Leachl’”);
CStr name(first + last);

Figure 7.2 illustrates how the addition operation works. Note that the value of the expression, first + last, is stored in a separate CStr object. The operator+ function creates this object and then returns it as a CStr object containing “Archie Leach”. This is a temporary object, and the compiler will destroy it when it is no longer needed.


Figure 7.2  Mechanics of a call to operator+.

And the Rest... (Other Addkion Functions)

The other operator+ functions for the CStr class look similar to the first operator+ function shown in the previous two sections.

CStr operator+(CStr str, char *s) {
   CStr new_string(str);
   new_string.cat(s);
   return new_string;
}

CStr operator+(char *s, CStr str) {
   CStr new_string(s);
   new_string.cat(str.get());
   return new_string;
}

All these operator+ functions look similar. In every case, the general procedure for evaluating string addition is basically the same:

1.  Create a new CStr object, initialized with the contents of the first operand.
2.  Concatenate the contents of the second operand.
3.  Return the resulting CStr object.


Previous Table of Contents Next
[an error occurred while processing this directive]

Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.