Please help me. I read many books and they talk: protected member can be accessed from member in same class, friend of own class, derivative class and friend of derivative class. I write code on codeblocks, all things are right, but friend of derivative class is wrong. Why ? Please help me. Here's my code
------------------
Small scope problem you have there. Just because something is a friend doesn't mean that the scope automatically changes. You still need to use :: or some equivalent.
EDIT: Also... erm... how is areal supposed to know which object it's accessing? It doesn't seem to take any arguments and it's not a member function...
@Disch(3141) - Don't remind what I wrote. Just I want to know how to fix this error.
@Albatross (1310) - You said have to add scope operator ::, mean
1 2 3
int Polygon::area1(){
....
}
But impossible. Because it's friend function, not member of Polygon. And when I add a class, which is friend of Rectangle, nothing to change. Can you clearly explain ?
but what polygon? How do you expect to use this function?
For example:
1 2 3 4 5 6 7
Polygon a;
Polygon b;
cout << a.area(); // gets the area of 'a'
cout << b.area(); // gets the area of 'b'
cout << area1(); // gets the area of ??? what???
In order to get the area of a polygon, you need a polygon!
You can pass the polygon to the function:
1 2 3 4
int area1(const Polygon& poly)
{
return poly.w * poly.w;
}
I want to explain more: how to friend of derived class can access to protected member of base class. I found example on ibm, but they use pointer. I want to use above simple example. Certainly, I know how to repair to function area can access variable w and h. But in this examle, why area1 cannot?
Not to interrupt the topic but according to Scott Meyers Effective C++ book, always try to use reference variables instead of pointers. Reason being the pointer could be NULL and then if you did not check and de-reference it, you can get error. Reference variables at run-time always point to some object so it is safe not to perform any NULL pointer check in your code.