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

Jonathan picture Jonathan · Oct 20, 2009 · Viewed 23.9k times · Source

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?

Answer

RED SOFT ADAIR picture RED SOFT ADAIR · Oct 20, 2009

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.