functors!

I compile the following code, suggested by someone, but i get the following compilation error:
 
sort_ba.cpp:8:27: error: passing ‘const bankAcct’ as ‘this’ argument of ‘double bankAcct::getBalance()’ discards qualifiers

Why? Does that mean I cannot use pass-by-reference inside the functors? in addition, why do i need to put the qualifier 'const' before the reference?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  1 #include <iostream>
  2 #include "bank_acc.cpp"
  3 #include <vector>
  4 #include <algorithm>
  5 using namespace std;
  6
  7 bool richer (const bankAcct& ba1, const bankAcct& ba2){
  8     return ba1.getBalance() > ba2.getBalance();
  9 }
 10
 11 int main(){
 12     vector<bankAcct> baV;
 13
 14     double balance;
 15     for (int i = 1; i <= 5; i++){
 16         cout << "Bank acct No." << i << endl;
 17         cout << "Balance: ";
 18         cin >> balance;
 19         baV.push_back(bankAcct (i, balance));
 20     }
 21
 22     cout << endl << "Sort bank accts in terms of balance in descending order.\n";
 23     sort(baV.begin(), baV.end(), richer);
 24     for (int i = 0; i < baV.size(); i++)
 25         cout << baV[i].toString() << endl;
 26
 27     return 0;
 28 }
const before the reference means you will not be modifying the object that the reference is referring to. On a cont-reference you can only call member functions marked as const (meaning the function does not modify the object). You should mark getBalance() with const.
1
2
3
4
5
6
class bankAcct
{
	...
	int getBalance() const;
	...
};
Last edited on
I see no functors in your code. A functor is a class with an overloaded operator().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <ostream>

class Say {
public:
    void operator () (const char *message) const
    {
        std::cout << "Say! " << message << std::endl;
    }
};

int main()
{
    Say s;

    s("Hello, World!");
    s("Beautiful day!");
}

When I omit 'const', i receive some other compilation error. Why must I put 'const'?
@jinanzhaorenbo
Because the comparison function is not supposed to modify the objects.
Last edited on
Topic archived. No new replies allowed.