0

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.

1
  • Unrelated - having a variable in the function that has the same name as the function does not help clarity (or maintainability).
    – Peter
    Commented Oct 4, 2022 at 12:53

1 Answer 1

2

From Protected_member_access (emphasis mine):

A protected member of a class is only accessible

  1. to the members and friends of that class;
  2. 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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.