On Mon, 19 May 2008 22:11:35 -0400, Victor Bazarov wrote:
utab wrote:
Dear all,
In a question in the highly recommended book Accelerated C++, it is
asked to change a const function into a plain function. After on the
reader is expected to find which function(s) should change.
The function to change is
original version
std::string name() const { return n; }
And this function is called from a predicate function which is passed
to a sort for vector:
original version
bool compare( const Student_info& x, const Student_info& y)
{
return x.name() < y.name();
}
and somewhere in the code sort is called for vector
sort(vec.begin(),vec.end(),compare)
Turning the name into a plain non-const function requires the change
of the const parameters of the compare function because const objects
can call const member functions. But making this change does not
solve my problem. I am getting an error(which is not that helpful
from g++) from the sort function and compare predicate. If someone
wants the whole code(might be a bit long though), I can paste it but
I wanted to ask it directly from the above explanation.
Can somebody help me to figure this problem out?
Here is what you have
struct foo {
int bar() const;
};
Here is what the exercise expects you to implement instead:
int bar(foo const&);
A member function takes a hidden argument - the object for which it
is called (you can either think it's a pointer or a reference, it
doesn't matter, really). A non-member function has to have an open
argument (there is nothing hidden in it).
V
Thanks for the answer, I tested something simple with this code
#include <cstdlib>
#include <iostream>
#include <list>
#include <sstream>
#include <map>
using namespace std;
struct foo{
foo():a(0){}
foo(int A):a(A) {}
//int bar() const {return a;};
int bar() {return a;};
private:
int a;
};
//void test_function(const foo &f)
void test_function(foo &f)
{
cout << f.bar() << endl;
}
int main()
{
foo fobj(5);
test_function(fobj);
return 0;
}
I commented out the const function and replaced that with a non-const
function. It works as intended but I am still not clear what is the
difference for my original problem. That is conceptually the same(or at
least that is what I think). I am trying to call a non-const member
function from inside a non-member function.
function has two arguments, passed by a reference, both const. Why are