"Jason Heyes" <ja********@optusnet.com.au> wrote in message news:<41**********************@news.optusnet.com.a u>...
class Rectangle
{
double width, height;
public:
double get_width() const { return width; }
double get_height() const { return height; }
void set_width(double width) { this->width = width; }
void set_height(double height) { this->height = height; }
};
Here's what I would have done:
#include "Helper.h"
class Rectangle {
ATTR_BBB(width, double);
ATTR_BBB(height,double);
};
I could then work with a rectangle as follows:
Rectangle r;
r.width(5.0); // sets the width to 5
cout << r.width(); // prints the width
cout << r._width; // tries to access the (protected) width member
directly.
Inside of my Helper.h file, I have definitions for automatically
declaring a protected member, along with accessor and modifier
functions. ATTR means I'm declaring an attribute, and the three Bs
are codes that determine whether the member, accessor, and modifier
functions work with base types, pointers, or references (B is for base
type, P for pointer, R for reference).
Here is the definition of ATTR_BBB:
#define ATTR_BBB(n,t) \
public: typedef t T_##n; \
t n() const { return _##n; } \
void n(t v) {_##n = v; } \
protected: t _##n
And also, FYI, here is the definition for ATTR_PRR, which has a
pointer to a type for its protected member, and the accessors and
modifiers deal with references:
#define ATTR_PRR(n,t) \
public: typedef t T_##n; \
t & n() { return * _##n; } \
const t & n() const { return * _##n; } \
void n(t & v) { _##n = & v; } \
protected: t * _##n
Cryptic, huh? Gotta love C. (## is the token pasting pre-processor
operator. _##n translates to "_width", or whatever)
Anyway, don't listen to those who tell you to just declare it as a
struct. I once made a coordinate class with public x and y members,
and, you guessed it, far into the project I came across a case that
required special handling for accessing the x and y values. If I had
been using accessors / modifiers, it would've been a trivial
modification, but instead it required a whole day of going through the
code. With inlined accessors and modifiers, there is zero performance
penalty associated with using them, and if you have a set of
accessor/modifier maker macros (like ATTR_BBB above), then you can
create them with a single line as well, making it just as terse and
readable.
Seems pretty compelling to me. Use accessor / modifier methods.
OH UNLESS UR SUPER LEET AND NEVER MAKE MISTAKES then you can do
whatever you want do it the oldsk00l C way lolol