problem with passage by const&

hi,
i'm trying to avoid the copy made during the appel of a function by using const&,

But it results a compilation error,

here is a function, it works with <Compteur c> as argument,

But when i add const& i get the following;(i don't understand it)

error: passing 'const Compteur' as 'this' argument of 'unsigned int& Compteur::Val()' discards qualifiers [-fpermissive]|

1
2
3
4
void afficher(Compteur const& c)
{
  cout << "Position : " << c.Val() << endl;
}

Val() is the getter of a private unsigned int called val.

thank u.
Last edited on
Please use code tags when posting source code. See this article:
http://www.cplusplus.com/articles/jEywvCM9/

It looks that Compteur::Val() is not a const member function.
A const member function has a const suffix and "promises" not to change member data.
When you pass an object by a const reference, you can only call const member functions.

http://isocpp.org/wiki/faq/const-correctness#const-member-fns

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Example
{
public:

    // non-const member function
    void func1()
    {
    }

    // const member function
    void func2() const
    {
    }

    unsigned int Val() const
    {
        // ...
    }
};

Last edited on
Thank you so much,"twice";
Sorry for not using code tags.
Topic archived. No new replies allowed.