0

I'm trying to make a function in DataBase namespace declared in DataBase.h file with implementation in DataBase.cpp that needs an access to a protected member of Collection class.

Here is what i currently have

Collection.h:

class Collection
{
   ...
protected:
   string name;
   friend Collection& DataBase::getCollection(string name);
};

DataBase.h:

namespace DataBase {
    ...
    Collection& getCollection(std::string collectionName);
}

DataBase.cpp:

namespace DataBase {
    ...
    Collection& getCollection(std::string collectionName)
    {
        for (auto& collection : _collections)
            if(collection.name == collectionName)
            {
               ...
            }
    }

}

The problem is I can't access name property.

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
  • Nope, a friend class/function should be able to access even private members. – stefan.gal Jun 01 '20 at 10:27
  • `DataBase::getCollection()` uses members of class `Collection` (like `collection.name`), so a definition of that class needs to be visible to the compiler before that point. – Peter Jun 01 '20 at 11:57

1 Answers1

0

You have to forward declare the friend function including namespace. I do not know how you are using _collections, so I changed the example a bit and I put everything in one file to start with something that works.

#include <string>
#include <vector>
using namespace std;

class Collection;

namespace DataBase {  
    Collection* getCollection(std::vector<Collection>& collections, std::string collectionName);
}

class Collection
{
protected:
  string name;
  friend Collection* DataBase::getCollection(std::vector<Collection>& collections, std::string name);
};


namespace DataBase {
  Collection* getCollection(std::vector<Collection>& collections, std::string collectionName)
  {
    for (auto& collection : collections)
      if (collection.name == collectionName)
      {
        return &collection;
      }
    return nullptr;
  }
}
stefan.gal
  • 302
  • 2
  • 6