c++ constant function in class

Viewed 147

Hello can someone please explain what does the const means in front of function declaration like so :

const void function(parameters);

I know, it means you can't modify what it returns, but how are we able to modify, what it returns? Thanks for any kind of reply.

2 Answers

It means exactly nothing. The function does not return anything so the const modifier modifies nothing.

To answer what probably was asked, you can return object, pointer or reference. If you don't want these to be modified by caller, then you use const.

I.e. something like that:

char *bar() {
  static char buf[100];
  ... some code ...
  return buf;
}

const char *foo() {
  static char buf[100];
  ... some code ...
  return buf;
}

b = bar();
*b = 'A'; // OK
f = foo();
*f = 'A'; // Error

Same goes with references and objects. Objects can be useful to declare const even by value because some objects can share common data even when copied.

BTW: This is not constant functions, but functions returning constant value. Constant functions is completely different thing.

Related