[Help with OOP] Passing object by reference using const modifier

 

In order to prevent changing of a parameter passed by reference, use the const modifier

Everything is clear here:

class CTest
  {
private:
   int property;
public:
   void changeProperty(int newValue) { property = newValue; }
  };

void OnStart()
  {
   CTest obj;
   obj.changeProperty(1);
   testFunc(obj);
  }

void testFunc(const CTest &a_obj)
  {
   a_obj.changeProperty(2); // Compilation error: 'changeProperty' - call non-const method for constant object
  }

But I can change the object in this way:

class CTest
  {
private:
   int property;
public:
   void changeProperty(int newValue) { property = newValue; }
   int  getProperty()                { return(property);    }
  };

void OnStart()
  {
   CTest obj;
   obj.changeProperty(1);
   testFunc(obj);
   Alert("obj.getProperty = ", obj.getProperty());
  }

void testFunc(const CTest &a_obj)
  {
   CTest* sameObj = (CTest*)GetPointer(a_obj);
   sameObj.changeProperty(2);
  }

That is, the const modifier protects against accidental change. But if you wish, you can change the passed object. Do I understand correctly?

 

Actually I just want to understand why the author uses const here:

void CRSIAverage::SetRSIPointers(const CRSIIndividual &rsi_objects[])
{
   int total = ArraySize(rsi_objects);
   ArrayResize(rsi_indicators, total);

   for (int i=0; i<total; i++)
      rsi_indicators[i] = (CRSIIndividual*)GetPointer(rsi_objects[i]);
}

It's just "good manners" and the const does not affect anything? Or is there some sence here that I don't know?

Code taken from this article.

Complex indicators made easy using objects
Complex indicators made easy using objects
  • www.mql5.com
This article provides a method to create complex indicators while also avoiding the problems that arise when dealing with multiple plots, buffers and/or combining data from multiple sources.
 
Vladislav Boyko:

In order to prevent changing of a parameter passed by reference, use the const modifier

Everything is clear here:

But I can change the object in this way:

That is, the const modifier protects against accidental change. But if you wish, you can change the passed object. Do I understand correctly?

Yes. It's to avoid simple error, as they will be caught by the compiler. const usage is rather limited in mql5.
 
Vladislav Boyko #:

Actually I just want to understand why the author uses const here:

It's just "good manners" and the const does not affect anything? Or is there some sence here that I don't know?

Code taken from this article.

You can't modify the objects through rsi_objetcs identifier.
 
Alain Verleyen #:
You can't modify the objects through rsi_objetcs identifier.

Thanks a lot!

Reason: