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:

  1. returning pointer suggest nullptr returned (but won't be). reference can't null, user knows they'll valid object (assuming behaved).
  2. 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

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -