Friend member function without class declaration

251 views Asked by At

There is probably a really easy fix for this but it's boggling me currently. So, I'm writing C++ classes to the effect of:

Header.h:

#pragma once
//...
class arrayObj
{
private:
   // some variables...
public:
   //constructor, destructor, getters, etc...
   friend void objManager::foo();
};
//...
class objManager
{
private:
   //...
   std::vector<std::shared_ptr<arrayObj>> array;
public:
   void foo();
   //other methods...
};

Now, as-is, my compiler will not find the class declaration of objManager (or the member function) declared for the friend inclusion. However, with the objManager declaration placed prior to the arrayObj, the arrayObj is no longer declared for the internal vector of shared pointers. Is there any way to forward declare objManager in this instance or otherwise solve this issue without dismantling the objManager into separate classes?

1

There are 1 answers

0
Barry On BEST ANSWER

You need to forward-declare arrayObj, then put the full definition of the objManager, and then finally the definition of arrayObj:

class arrayObj;

class objManager {
    std::vector<std::shared_ptr<arrayObj>> array; // OK, fwd-declare is fine for this

public:
    void foo();

    // etc.
};

class arrayObj {
public:
    friend void objManager::foo();
    // etc.
};

In order to declare a friend, that method has to already have been seen, so it has to go first. The forward declaration is a consequence of the vector.