0

Hello I am working with C++ built-in algorithms. I have this code here:

#include <string>
#include <algorithm>
#include <iterator>
using namespace std;

bool isDon(string& name) const {
    return name == "Don";
}

string names[] = {"George", "Don", "Estelle", "Mike", "Bob"};

int main() {
    string* ptr;
    ptr = find_if(names, names+5, isDon);

    return 0;
}

When I run this program, compiler gives me an error ,in which my isDon() function decleration resides, which says that I cannot use a cv-qualifier in that function decleration. Why is that?

Bora Semiz
  • 223
  • 2
  • 14

5 Answers5

3

const affects (formally, qualifies) the this pointer. Freestanding functions don't have it: only non-static member functions do.

edmz
  • 8,220
  • 2
  • 26
  • 45
2

The const qualifier only refers to member functions and declare that the function does not modify the object over which that member function is invoked. The semantic is implemented by making this a T const*.

For a free function this just doesn't make sense.

Shoe
  • 74,840
  • 36
  • 166
  • 272
2

This function should be declared without the trailiing const. It is a free function and doesn't belong to a class, so it is not meaningful for the function to be const.

bool isDon(string const& name) {
    return name == "Don";
}

Note that you can also use a lambda of the form

ptr = find_if(names, names+5, [](string const& name){ return name == "Don"; });
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

Making a free-standing function const doesn't make any sense, only class or structure member functions can be const.

That's because the const tells the compiler that the (member) function will not modify the object instance.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

The const qualifier after a function name is for a function INSIDE a class; this function is Not Part of a Class; the const is telling the compiler the function does not modify members inside the class.

" A const qualifier can be used only for class non static member functions"

const type qualifier soon after the function name

Community
  • 1
  • 1
A B
  • 4,068
  • 1
  • 20
  • 23