Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getter and setter, pointers or references, and good syntax to use in c++?

I would like to know a good syntax for C++ getters and setters.

private:
YourClass *pMember;

the setter is easy I guess:

void Member(YourClass *value){
  this->pMember = value; // forget about deleting etc
}

and the getter? should I use references or const pointers?

example:

YourClass &Member(){
   return *this->pMember;
}

or

YourClass *Member() const{
  return this->member;
}

whats the difference between them?

Thanks,

Joe

EDIT:

sorry, I will edit my question... I know about references and pointers, I was asking about references and const pointers, as getters, what would be the difference between them in my code, like in hte future, what shoud I expect to lose if I go a way or another...

so I guess I will use const pointers instead of references

const pointers can't be delete or setted, right?

like image 270
Jonathan Avatar asked Oct 20 '09 18:10

Jonathan


2 Answers

As a general law:

  • If NULL is a valid parameter or return value, use pointers.
  • If NULL is NOT a valid parameter or return value, use references.

So if the setter should possibly be called with NULL, use a pointer as a parameter. Otherwise use a reference.

If it's valid to call the getter of a object containing a NULL pointer, it should return a pointer. If such a case is an illegal invariant, the return value should be a reference. The getter then should throw a exception, if the member variable is NULL.

like image 189
RED SOFT ADAIR Avatar answered Sep 19 '22 00:09

RED SOFT ADAIR


The best thing is to provide a real OO interface to the client that hides implementaton details. Getters and Setters are not OO.

like image 30
DevFred Avatar answered Sep 18 '22 00:09

DevFred