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.
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);
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&
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With