Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friend function not working

Tags:

c++

c++11

In the following code I am trying to have a friend function access the private member of the class. To my understanding I am correctly declaring it as a friend function, but VS2012 is giving me the error:

error C2248: 'X::S::s_' : cannot access private member declared in class 'X::S'

Can anyone suggest what I am doing wrong? This is the simplest example that demonstrates the compiler error that I could come up with.

namespace X
{
    class S
    {
        friend std::string r(X::S &s);
        std::unique_ptr<std::istream> s_;
    };
}
std::string r(X::S &s)
{
    auto& x = s.s_;
    return "";
}
like image 293
Graznarak Avatar asked Dec 12 '22 12:12

Graznarak


1 Answers

You're defining ::r, not X::r, which is what your friend declaration is for. Move the function into the namespace alongside the class, or define it right inside the class, though that can be problematic with a class template or keeping the class definition concise. If the definition is in a separate file, you can still enclose it with the namespace like you do the class to add it to the namespace. I would also suggest removing the X:: qualification as it's already in X.

namespace X
{
    class S
    {
        friend std::string r(S &s);
        std::unique_ptr<std::istream> s_;
    };

    std::string r(S &s)
    {
        auto& x = s.s_;
        return "";
    }
}
like image 81
chris Avatar answered Dec 21 '22 00:12

chris