Pass an array of class objects as const to a function to prevent any modification of the class objects

StackOverflow https://stackoverflow.com/questions/23522121

  •  17-07-2023
  •  | 
  •  

Frage

Hi I am new to C++ and this question might be simple. Please bear with me :)

I have an array of class Foo ==> Foo foo_objects[4];

If I want to pass this array to a function:

function declaration: void do_something(Foo *foo_objects_ptr);
function call       : do_something(foo_ojects); 

Now I want to pass this array of foo_objects to the function and prevent any modification of these objects.

function declaration: void do_something(const Foo *foo_objects_ptr);
function call       : do_something(foo_ojects);

Is this the right way to do it? Does this guarantee that all four objects in the foo_objects will be protected from any modification inside the do_something method or only the first object in the array enjoys const privileges?

War es hilfreich?

Lösung

foo_objects_ptr + i has the same type as foo_objects_ptr, so that is also a const pointer.

So foo_objects_ptr[i] is const for all i.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top