why use "protected" instead of "private"?

J

Jordan Taylor

I am confused about protected member functions and objects. Is there
any particular advantage of declaring members protected?
 
B

benben

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
 
A

al pacino

Jordan said:
I am confused about protected member functions and objects. Is there
any particular advantage of declaring members protected?

hi jordan,

well protected members can be manipulated by the functions of the
derived
class thats it.

however according to principle of least privelage(C++ how to program by
Deitel)
always use private data members if derived class wants to use those
values
provide function/s in the base class that acts as an interface for the
private data.
 
B

Backer

Protected keywords are only used in the inheritance context. The base
class protected variables can be accessed in the derived class also.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top