Software Development Methodology> Guidelines for new implementations>  Getters and setters

Release Information

Project: Siconos
Internal Release Number: 1.0
Last update: September 15, 2005
Related Documents:


next up previous

Getters and setters

Since object members are private data, getters and setters functions should be implemented. They should respect the following rules:
  • be implemented as inline functions when possible (ie when implementation is simple and short enough)
  • name ended by "Ptr" when function handle pointers
  • respect previous remarks about function members
For "classical" type (ie non pointer) object members, we set two functions, one to get the value without any possibility to change it (ie const attribute) and the other to set the value. A third one may possibly be added, to return the address of the member.
For pointer type members, four functions are implemented:
  • 2 to get/set the pointer
  • 2 to get/set the value of the pointed object
Finally, the corresponding header file looks like:
	public:
// -- GETTERS AND SETTERS --

//
- for non pointers members -
//
get objectMemberA

inline const typeObject getObjectMemberA() const
{ return objectMemberA; }

// assign newValue to objectMemberA
inline void setObjectMemberA(const
typeObject& newValue) { objectMemberA = newValue; }

// return a pointer on objectMemberA (optional)
inline const typeObject getObjectMemberAPtr() const
{ return &objectMemberA; }

// - for pointer type members -

//
a - get the value of pointed object
inline const typeObject getObjectMemberB() const
{ return *objectMemberB; }

// b - get the pointer
inline typeObject* getObjectMemberBPtr() const { return objectMemberB; }

// c - set the value of the pointed object
inline void setObjectMemberB(const typeObject& newValue) { objectMemberB = newValue; }

// d - set the pointer
inline void setObjectMemberBPtr(typeObject newPtr)
{ if(isObjectMemberBAllocatedIn) delete objectMemberB; objectMemberB = newPtr; }

// -- PRIVATE/PROTECTED MEMBERS --
protected:

typeObject ObjectMemberA;
typeObject* ObjectMemberB;
bool isObjectMemberBAllocatedIn;
Some remarks:
  • the get function (a), return a const, that means it can not be an lvalue, and so we can not write getObjectMemberB = ...
  • (a) and (b) are const, that ensure they do not modify data members.
  • input argument in (c) is const and so can not be modified.
  • a call to (d) means that any change on objectMemberB implies change on newPtr.
  • for (d) function, it is necessary to first delete the data member and then to reassign it, this to avoid a ``double'' new (one on newPtr and another on objectMemberB), leading to error when call to delete at the end.

next up previous