On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

### Messenger

The most trivial of these is the messenger,[136] which packages information into an object which is passed around, instead of passing all the pieces around separately. Note that without the messenger, the code for translate( ) would be much more confusing to read:

//: C10:MessengerDemo.cpp
#include <iostream>
#include <string>
using namespace std;

class Point { // A messenger
public:
int x, y, z; // Since it's just a carrier
Point(int xi, int yi, int zi) : x(xi), y(yi), z(zi) {}
Point(const Point& p) : x(p.x), y(p.y), z(p.z) {}
Point& operator=(const Point& rhs) {
x = rhs.x;
y = rhs.y;
z = rhs.z;
return *this;
}
friend ostream&
operator<<(ostream& os, const Point& p) {
return os << "x=" << p.x << " y=" << p.y
<< " z=" << p.z;
}
};

class Vector { // Mathematical vector
public:
int magnitude, direction;
Vector(int m, int d) : magnitude(m), direction(d) {}
};

class Space {
public:
static Point translate(Point p, Vector v) {
// Copy-constructor prevents modifying the original.
// A dummy calculation:
p.x += v.magnitude + v.direction;
p.y += v.magnitude + v.direction;
p.z += v.magnitude + v.direction;
return p;
}
};

int main() {
Point p1(1, 2, 3);
Point p2 = Space::translate(p1, Vector(11, 47));
cout << "p1: " << p1 << " p2: " << p2 << endl;
} ///:~

The code here is trivialized to prevent distractions.

Since the goal of a messenger is only to carry data, that data is made public for easy access. However, you may also have reasons to make the fields private.

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

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