Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't this friend function access the private variables?

Tags:

c++

class

friend

class Student{
public:
Student(int test)
:key(705)
{
    if(test == key)
    {cout << "A student is being verified with a correct key: "<< test << endl;
    allow=1;
    }
    else
    {
        cout << "Wrong key" ;
    }
}

friend void printResult();


private:
const int key;
int allow;


};

void printResult()
{
 if(allow==1)
 {
   cout<< " Maths: 75 \n Science:80 \n English: 75" << endl;
  }
}

int main()
{
int testkey;
cout << "Enter key for Bob: ";
cin >> testkey;

Student bob(testkey);

printResult();

}

The function printResult can't seem to access the variable allow, which is private, from the Student class. Did I prototype the printResult in the wrong place or was the syntax wrong? AFAIK, we can prototype friends anywhere in the class.

like image 583
user2477112 Avatar asked Dec 06 '22 07:12

user2477112


2 Answers

printResult is not a member function, so you need to give it a Student instance to act on. For example

void printResult(const Student& s)
{
 if(s.allow==1)
 {
   cout<< " Maths: 75 \n Science:80 \n English: 75" << endl;
  }
}

then

Student student(1);
printResult(student);
like image 116
juanchopanza Avatar answered Dec 21 '22 22:12

juanchopanza


That's because allow belongs to an instance of the class, but no instance is being referred to.

You should probably make printResult a member function of the class instead of making it an external function or make the function take a reference to a Student instance so you can access the allow member via the instance.allow where instance is a parameter of type const Student&.

like image 30
user123 Avatar answered Dec 21 '22 23:12

user123