Reputation: 39
Talk is cheap, show you the code:
#include <string>
#include <vector>
using namespace std;
class Message {
protected:
virtual string json() const = 0;
};
class _messageChain_ final: public Message {
public:
string json() const override;
private:
vector<Message *>messages;
};
string _messageChain_::json() const
{
string json;
for ( Message *msg : messages )
json += msg->json();
return json;
}
int main ( void )
{
}
When I tried to compiling it:
main.cpp: In member function ‘virtual std::string _messageChain_::json() const’:
main.cpp:21:21: error: ‘virtual std::string Message::json() const’ is protected within this context
21 | json += msg->json();
| ^
main.cpp:7:17: note: declared protected here
7 | virtual string json() const = 0;
I think the protected
will makes _messageChain_
be able to access the member (virtual string json();
) of Message, in the function string _messageChain_::json()const;
.
But it didn't.
If I add _messageChain_
as a friend to Message
or replace protected
with public
,it will work. If I add string _messageChain_::json()const;
as a friend, it won't work.
I'm confused why protected
and friend <function>
doesn't work but friend class _messageChain
does.
Upvotes: 0
Views: 102
Reputation: 218343
From Protected_member_access (emphasis mine):
A protected member of a class is only accessible
- to the members and friends of that class;
- to the members of any derived class of that class, but only when the class of the object through which the protected member is accessed is that derived class or a derived class of that derived class:
So you can access Message::json
only from a _messageChain_
object.
Upvotes: 2