Declaring property C++ by reference or pointer -
i want declare properties of class. thinking of creating private variables properties want in class.
and exposing private variables reference. have pointer can pass address of private variable. user of class can modify variable.
so way better via reference or pointer shown in example below?
class exampleclass { private: int age; public: //this function allows access via reference int& getagebyreference() { int& refage= age; return refage; } //this function allows access via pointer int* getagebypointer() { int* pointage= &age; return pointage; } }
return reference 2 reasons:
- returning pointer suggest
nullptr
returned (but won't be). reference can't null, user knows they'll valid object (assuming behaved). - returning pointer make user of function wonder ownership of object being pointed at. reference tells user can object , don't need kind of memory management.
whether should leaking internals of object @ matter.
Comments
Post a Comment