Kevin
Kevin

Reputation: 111

My friend function is not executing

I have declared a friend function in my header file, and defined it in my .cpp file, but when I compile I am told that the variables 'have not been declared in this scope'. It's my understanding that when a function is labeled a friend of a class, that function is able to directly access all members of that class, so why would I get this error?

My .h file:

#ifndef EMPLOYEE_H
#define EMPLOYEE_H

#include<string>
using namespace std;

class Employee
{
  friend void SetSalary(Employee& emp2);

 private:

  string name;
  const long officeNo;
  const long empID;
  int deptNo;
  char empPosition;
  int yearOfExp;
  float salary;
  static int totalEmps;
  static int nextEmpID;
  static int nextOfficeNo;

 public:
  Employee();
  ~Employee();
  Employee(string theName, int theDeptNo, char theEmpPosition, int theYearofExp);
  void Print() const;
  void GetInfo();
};

#endif

function in my.cpp file

void SetSalary(Employee& emp2)
{

  while (empPosition == 'E')
    {
      if (yearOfExp < 2)
        salary = 50000;
      else
        salary = 55000;
    }
}

Note: In my Main.cpp, I am creating an object 'emp2'. This is being passed as a parameter into the function.

Upvotes: 0

Views: 72

Answers (1)

juanchopanza
juanchopanza

Reputation: 227458

empPosition, yearOfExp and salary are members of the Employee class, so you need

while (emp2.empPosition == 'E') ....
//     ^^^^

and similarly for the expressions involving yearOfExp and salary. friend functions are non-member functions, so they can only access data members of the class they are friends of via an instance of that class (emp2 in this case).

Upvotes: 4

Related Questions