I'm having difficulties with get functions. Maybe I have misunderstood something in this class, but how can I get the name if I have no parameters in a get function? Thank you.
But I don't understand what am I supposed to do for the first constructor because I have got only username. Is it for replacing the old one with the new?
But this seems incorrect because I get these errors:
event.cpp:34: error: request for member ‘username’ in ‘((Event*)this)->Event::owner’, which is of non-class type ‘User*’
event.cpp:34: error: request for member ‘getUsername’ in ‘owner’, which is of non-class type ‘User*’
event.cpp:35: error: request for member ‘name’ in ‘((Event*)this)->Event::owner’, which is of non-class type ‘User*’
event.cpp:35: error: request for member ‘getName’ in ‘owner’, which is of non-class type ‘User*’
event.cpp:36: error: request for member ‘surname’ in ‘((Event*)this)->Event::owner’, which is of non-class type ‘User*’
event.cpp:36: error: request for member ‘getSurname’ in ‘owner’, which is of non-class type ‘User*’
I have replaced ' . ' with ' -> ' . Now I get these errors:
User.h:13: error: ‘std::string User::username’ is private
event.cpp:34: error: within this context
User.h:13: error: ‘std::string User::username’ is private
event.cpp:34: error: within this context
User.h:14: error: ‘std::string User::name’ is private
event.cpp:35: error: within this context
User.h:14: error: ‘std::string User::name’ is private
event.cpp:35: error: within this context
User.h:15: error: ‘std::string User::surname’ is private
event.cpp:36: error: within this context
User.h:15: error: ‘std::string User::surname’ is private
event.cpp:36: error: within this context
I try to use get methods. I have used getName(),getUsername() and getSurname() functions that I have implemented for the User class, but it does not work, I get the same errors :( What I have done is:
"You directly accessed members on both sides of =, so you need both setters and getters. " what did you mean with this sentence explicitly? hamsterman.
zulfikar, consider struct Object{ private: int x; };. Now if in your main() you have Object o, and write o.x, you'll get an error saying that you can't access private members. Thus you have to write two functions. One for getting x : int Object::GetX(){ return x; } and one for setting it : void Object::SetX(int i){ x = i; }. Now while code o.x = 5; int a = o.x; was not correct, o.SetX(5); int a = o.GetX(); is fine. You could also write a getter which returns a reference: int& Object::Get(){ return x;} and then in main() : o.Get() = 5; int a = o.Get();.
Note, however, that none of getters or setters in this post so far are meaningful. They do not provide any encapsulation as x can be freely given any value. If you didn't have setter at all, or if it was void Object::SetX(int i){ if(i > 0) x = i; else x = 0; }//allows x to have only non-negative values it would make much more sense to have them (as opposed to making x public).