c++ - Return a reference to an attribute (GCC) -


i'm using gcc first time (previously msvc) , have problems returning reference variable in class. here code:

class foo { public:    const int& getmyvar() const   {       return mmyvar;   }  private:   int mmyvar; }; 

if there bigger data structure simple int can't imagine have return copy instead of reference.

here compile error:

error: invalid initialization of reference of type 'int&' expression of type 'int'

it great if me , show me how can solve problem.

given following code, minor variant of class (constructor added; semicolon added after class) , simple main(), compilation error:

z1.cpp: in function ‘int main()’: z1.cpp:19:26: error: invalid initialization of reference of type ‘int&’ expression of type  ‘const int’ 

line 19 const int &v2 = f.getmyvar(); line. remove reference mark, , fine.

class foo { public:    foo(int n = 0) : mmyvar(n) {}   const int& getmyvar() const   {       return mmyvar;   }  private:   int mmyvar; };  int main() {     foo f;     int  v1 = f.getmyvar(); // copies result     int &v2 = f.getmyvar(); // error: must const     const int &v3 = f.getmyvar(); // ok long there's default constructor     return v1 + v2 + v3; } 

Comments