This post is the continuation of the previous C++ error's post.
I was getting another error as specified in the title while running the below program, and I wasn't sure how to resolve this and was idle for a few minutes searching in stackoverflow.
#include <iostream> class army // Class declaration { int number_suffix; //Member Variable string key; void enrollment(string name, int age) {key = name; number_suffix = age;} void retirement() // Member Functions {cout << key << " is retiring";} }; int main() { army a1; // Object creation and Memory allocation a1.enrollment("Shirley", 31); a1.retirement(); return 0; }
In function 'int main()':
Line 8: error: 'void army::enrollment(std::string, int)' is private
compilation terminated due to -Wfatal-errors. |
Later, realized that this error is something to do with private & public access.
By default, the members of the class is private. It does mean that it is not accessible outside of the class. If the function members need to be used in the main(), these members should be public.
#include <iostream> class army // Class declaration { public: int number_suffix; // Member Variable string key; void enrollment(string name, int age) {key = name; number_suffix = age;} void retirement() // Member Functions {cout << key << " is retiring";} }; int main() { army a1; // Object creation and Memory allocation a1.enrollment("Shirley", 31); a1.retirement(); return 0; }
Here, I want to protect my member variables, so I changed the access specifier to private. As I want to access only the member functions, I declare them as public.
#include <iostream> class army // Class declaration { private: int number_suffix; // Member Variable string key; public: void enrollment(string name, int age) {key = name; number_suffix = age;} void retirement() // Member Functions {cout << key << " is retiring";} }; int main() { army a1; // Object creation and Memory allocation a1.enrollment("Shirley", 31); a1.retirement(); return 0; }
From this post, we learnt that the default access specifier is private for any class.
Comments
Post a Comment