Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to Member Variable in Function declaration in C++?

Tags:

c++

I'm trying to do something like the following:

class FOO {
 void bar(int& var = m_var) {
   // ....
 }
 int m_var;
};

Why doesn't this compile? Why didn't they program this into the language? Is there any way to mimic this behavior?

like image 207
roxors Avatar asked Jul 03 '26 08:07

roxors


1 Answers

This is not allowed because m_var is a member variable and needs to be accessed through the object.
It would compile successfully if m_var was a static member of the class.

A simple workaround is calling an overloaded function with same name or another member function through bar() (which is a member function & has access to m_var) and pass m_var as an parameter by reference.It will have the same effect you want to achieve.

like image 61
Alok Save Avatar answered Jul 04 '26 20:07

Alok Save



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!