-1

I've got a Parent Class and a Child Class. The Parent have a protected function called setId(int id). Now I want to make the setId function acessable by friend class of Child (lets call it Friend). Is this possible or do I have to reimplement the setId function inside the Child class and use the protected setId function of parent?

I've tried this with VS-Compiler and it works.

I use gcc and get "error: ‘void Parent::setId(int)’ is protected"

Class Parent

class Parent
{
public:
    Parent(){}

protected:
    void setId(int id){m_id=i}

    int m_id;
};

Class Child

#include "Parent.h"

class Child
        : public Parent
{
    friend class FriendClass;
public:
    Child(){}
};

Class Friend

#include "Child.h"

class FriendClass
{
public:
    FriendClass(){
      Child c;
      c.setId(1);
    }
};
Marcus
  • 1,910
  • 2
  • 16
  • 27

1 Answers1

1

Common wisdom holds that the right way is to upgrade access in Child:

class Child: public Parent {
public:
    void setId(int id) override { Parent::setId(id); } // public for Friend
};

The usual rationale is that this is brief and expresses clearly and precisely what's being made public, without publishing any other internals.

arnt
  • 8,949
  • 5
  • 24
  • 32