views:

268

answers:

1

In a previous Q&A (How do I define friends in global namespace within another C++ namespace?), the solution was given for making a friend function definition within a namespace that refers to a function in the global namespace.

I have the same question for classes.

class CBaseSD;

namespace cb {
class CBase
{
    friend class ::CBaseSD; // <-- this does not work!?
private:
    int m_type;
public:
    CBase(int t) : m_type(t) {};
};
}; // namespace cb

class CBaseSD
{
private:
    cb::CBase*  m_base;
public:
    CBaseSD(cb::CBase* base) : m_base(base) {};
    int* getTypePtr()
    { return &(m_base->m_type); };
};

If I put CBaseSD into a namespace, it works; e.g., friend class SD::CBaseSD; but I have not found an incantation that works for the global namespace.

I am compiling with g++ 4.1.2.

A: 

add the forward declaration like below

namespace {  
  // anonymous namespace declaration
  class CBaseSD;
}

then your normal

friend class CBaseSD;// no need of ::

works in CBase

ram kumar