954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to access static variables in friend functions

#include<iostream>
using namespace std;



class item
{
  int itemno;
  int itemprice;

public :
  static int total;
  void getprice();
  void printprice();
  friend void calculate(item a);
};
int item :: total=0;
void item :: getprice()
{
  cout<<"Print item number \n";
  cin>>itemno;
  cout<<"Print item price \n";
  cin>>itemprice;
  total++;
}

void item :: printprice()
{
  cout<<"item "<<itemno<<" itemprice "<<itemprice<<endl;
  cout<<total<<"\n";
}


void calculate(item a)
{

  total+=a.itemprice;

}


int main()
{
  item array[5];
  int i;
  for(i=0;i<2;i++)
  {
    array[i].getprice();
    calculate(array[i]);
  }
  for(i=0;i<2;i++)
  {
    array[i].printprice();
  }

}

see the above programme show error cos i cannot use static variable total in friend function properly........ how can i do this

lookforlohith
Newbie Poster
7 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

The compiler doesn't know where to look for total, so it looks for local variables and then global variables. If you want to access the static member, you have to qualify it with the class it's declared in:

item::total += a.itemprice;

Alternatively you can use the object to get to it as well:

a.total += a.itemprice;
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

thanks

lookforlohith
Newbie Poster
7 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You