Jordan said:
I am confused about protected member functions and objects. Is there
any particular advantage of declaring members protected?
If you want a particular member accessible from a class inheriting you
class but not the direct user then you should make the member protected.
For example, consider the classic shape hierarchy with drawing
capabilities. Naturally, the code dealing with drawing is encapsulated
in a separate class shape_drawer:
class shape_drawer
{
public: // provided for users
void set_color(const color&);
void apply_filter(const filter&);
virtual void draw(void) = 0;
protected: // provided for inheritors
void draw_line(point from, point to);
void draw_curve(const std::vector<point>& pts);
~shape_drawer();
};
Then the shape hierarchy can be augmented by deriving all concrete
shapes from shape_drawer
class circle: public shape, public shape_drawer
{
// ...
public:
// protected members in base are used to implement the following
// function for example:
void draw(void)
{
using namespace std;
vector<point> pts = get_coordinates();
draw_curve(pts);
}
//...
};
// protected members are kept away from user, as follows:
int main()
{
circle c;
c.set_color(color::red); // ok, shape_drawer::set_color is public
c.apply_filter(alpha_filter(0.50)); // ok
c.draw();
vector<point> p;
p.push_back(point(0, 0));
p.push_back(point(3, 4));
p.push_back(point(4, 5));
c.draw_line(p[0], p[1]); // error: calling protected member
c.draw_curve(p); // error: calling protected member
}
Regards,
Ben