Aditya P
Aditya P

Reputation: 1942

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"

Upvotes: 3

Views: 5227

Answers (5)

Mahesh
Mahesh

Reputation: 34625

Static variables don't belong to any particular instance of a class. Instead you may access them with a class name as Base::num to improve readability. Also, your friend function definition has a different signature than the one you declared.

Upvotes: 0

Murilo Vasconcelos
Murilo Vasconcelos

Reputation: 4827

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.

Upvotes: 4

6502
6502

Reputation: 114481

In C++ it's not enough to declare a static variable in the .h; you must also define it explicitly in a .cpp. You must add in the .cpp of the implementation

int Base::num;

What you got was a linker error because of this missing variable definition.

Upvotes: 0

Loki Astari
Loki Astari

Reputation: 264411

Different friends:

friend void setnum(Base obj); 
         //    ^^^  Not the same as vals!
       void setvals(Base obj)

Upvotes: 0

peoro
peoro

Reputation: 26060

Your free function is called setvals, but the Base's friend function is called setnum...

Besides you'll have to actually define the static variable, not just declare it.

Put:

int Base::num;

in a source file.

Upvotes: 4

Related Questions