Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Thinking in C++
Prev Contents / Index Next

Operator conversion

The second way to produce automatic type conversion is through operator overloading. You can create a member function that takes the current type and converts it to the desired type using the operator keyword followed by the type you want to convert to. This form of operator overloading is unique because you don’t appear to specify a return type – the return type is the name of the operator you’re overloading. Here’s an example:

//: C12:OperatorOverloadingConversion.cpp
class Three {
  int i;
  Three(int ii = 0, int = 0) : i(ii) {}

class Four {
  int x;
  Four(int xx) : x(xx) {}
  operator Three() const { return Three(x); }

void g(Three) {}

int main() {
  Four four(1);
  g(1);  // Calls Three(1,0)
} ///:~

With the constructor technique, the destination class is performing the conversion, but with operators, the source class performs the conversion. The value of the constructor technique is that you can add a new conversion path to an existing system as you’re creating a new class. However, creating a single-argument constructor always defines an automatic type conversion (even if it’s got more than one argument, if the rest of the arguments are defaulted), which may not be what you want (in which case you can turn it off using explicit). In addition, there’s no way to use a constructor conversion from a user-defined type to a built-in type; this is possible only with operator overloading.

Thinking in C++
Prev Contents / Index Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire