Search code examples
c++functionstaticfriendvar

Accessing static variable from a friend function


class Base
{
private:
    static int num; 
public:
    friend void setnum(Base obj); 
};

void setnum(Base obj)
{
    obj.num=4;  /* Error */
}

A friend function is supposed to have access to all the private data of a class. what am i missing here? I cant seem to access the the static variable from the friend function.

Error from codepad--> In function setnum(Base)': undefined reference to Base::num'

Error from visual studio--> error LNK2001: unresolved external symbol "private: static int Base::num"


Solution

  • You only declared the static variable num. You must to define it:

    class Base
    {
    private:
        static int num; 
    public:
        friend void setvals(Base obj); 
    };
    
    // This must be in a .cpp
    int Base::num;
    
    void setvals(Base obj)
    {
        obj.num=4;
    }
    

    This code works.

    Edit:

    Actually you can implement the setvals() function as follows:

    void setvals()
    {
        Base::num=4;
    }
    

    And at your Base class:

    friend void setvals(); 
    

    Because num is static.