Problem when using a protected function

Jan 18, 2015 at 9:11am
Hi all,

Please have a look at Graph.h file of here: http://www.stroustrup.com/Programming/Graphics/

There, both the void add(Point p) and void set_point(int i, Point p) in Shape class are in protected section.
Now in below code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <Simple_window.h>
#include <Graph.h>

using namespace Graph_lib;

//------------------------------------------------------------------------------
int main() {
	Simple_window win(Point(100,100),600,400,"lines");

	Graph_lib::Polygon poly;

	poly.add(Point(100,100));
	poly.add(Point(150,150));
	poly.add(Point(50,100));
	poly.set_point(1,Point(200,200));

	win.attach(poly);
	win.wait_for_button();
	return 0;
}


despite both are in protected I can use of add() function without any problem but not the set_point function! Why?

At that above code I get these two errors:

Error 8 error C2248: 'Graph_lib::Shape::set_point' : cannot access protected member declared in class 'Graph_lib::Shape' c:\users\cs\documents\visual studio 2012\projects\test_1\test_1\test_1.cpp 15

9 IntelliSense: function "Graph_lib::Shape::set_point" (declared at line 165 of "C:\Program Files\Microsoft Visual Studio 11.0\VC\include\Graph.h") is inaccessible c:\Users\CS\Documents\Visual Studio 2012\Projects\test_1\test_1\test_1.cpp 15


How to use set_point function please?
Jan 18, 2015 at 10:28am
khoshtip wrote:
despite both are in protected I can use of add() function without any problem but not the set_point function! Why?

The add function has been overridden in the Polygon class as public which is why you can call it on the Polygon object. The set_point function, on the other hand, has not been overridden and it is protected in the base class so that is why you are not allowed to call it.

khoshtip wrote:
How to use set_point function please?

Without making changes to Graph.h there is no way you can call that function.
Jan 18, 2015 at 12:01pm
Thank you very much for the answer.

But the protected part doesn't mean that all of its function can be called from a derived class? That is, Shape is base, and set_point() is protected, so this protected doesn't mean that from any class derived form base (here polygon from Shape) we can call the protected functions?
Jan 18, 2015 at 12:30pm
Yes, polygon can call Shape protected functions including set_point(). But no other classes/functions can. In particular, main() cannot call set_point(), so line 15 is an error.
Jan 18, 2015 at 1:44pm
So calling set_point is possible just inside the derived class, here polygon and in the definition of it which is inside the graph.h file and not outside the polygon, yes?
Jan 18, 2015 at 1:59pm
Yes. Only members of derived classes can call protected functions.
Jan 18, 2015 at 2:09pm
Thank you very much :)
Topic archived. No new replies allowed.