Here is the code that works:
#include <iostream> class Student { public: Student(int test) : key(705) { if(test == key) { std::cout << "A student is being verified with a correct key: "<< test << std::endl; allow=1; } else { std::cout << "Wrong key" ; } } friend void printResult(Student* student); private: const int key; int allow; }; void printResult(Student* student) { if(student->allow==1) { std::cout<< " Maths: 75 \n Science:80 \n English: 75" << std::endl; } } int main(int argc, char* argv[]) { int testkey; std::cout << "Enter key for Bob: "; std::cin >> testkey; Student bob(testkey); printResult(&bob); }
I changed it to keep the print function in global space (only based on how it looked the way you wanted). It accepts the Student * argument, and since it is declared as a friend, it will see the "allow" variable. This, however, is not the part of C ++ that you want to abuse. Be careful how you use a friend. Using it like this is dangerous in a larger code base. Global functionality is usually not suitable. Having a print function as an open member function in a student class is likely to be the best way to do something. Other answers provided code that shows this implementation. I decided to show you this implementation, because it seemed closer to what you were looking for in your question.
I also use 'std ::' when I refer to cout and endl. This eliminates the need to use 'namespace std;' on the top. This is just a good future programming practice for more complex projects.
source share