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

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -