43

I have a class Cache which has a function write specified as

bool write(const MemoryAccess &memory_access, CacheLine &cl);

I am calling this function like this.

const Cache *this_cache;
c = (a==b)?my_cache:not_cache;
c->write(memory_access,cl);

The above line is giving me following error

"passing ‘const Cache’ as ‘this’ argument of ‘bool Cache::write(const MemoryAccess&, CacheLine&)’ discards qualifiers [-fpermissive]."

the this argument is compiler specific which helps in code-mangling and breaking local namespace variable priority. But such a variable is not being passed here.

Yamaneko
  • 3,433
  • 2
  • 38
  • 57
prathmesh.kallurkar
  • 5,468
  • 8
  • 39
  • 50
  • Please try to fix your example: you talk about function `write`, then you call `read`. Where do you declare `memory_access` and `cl`? – betabandido May 26 '12 at 11:24
  • 1
    *the this argument is compiler specific which helps in code-mangling and breaking local namespace variable priority*??? – NPE May 26 '12 at 11:27

3 Answers3

52

Since c is of type const Cache *, you can only call const member functions on it.

You have two options:

(1) remove const from the declaration of c;

(2) change Cache::write() like so:

 bool write(const MemoryAccess &memory_access, CacheLine &cl) const;

(Note the added const at the end.)

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 3
    what is the significance of const at the end of the signature ?? What exactly do we mean when we say this is constant. Should it not be constant by default ?? – prathmesh.kallurkar May 26 '12 at 11:40
  • 2
    @prathmesh.kallurkar: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.10 – NPE May 26 '12 at 11:57
5

When you call a method via a pointer to an object, this object is implicitly passed to the method as this pointer. c probably has type const Cache*. Since method write is not declared as const, it has non-const this pointer accessible from its body requiring const qualifier of c to be discarded.

Alex Bakulin
  • 1,668
  • 11
  • 17
0

Also if your class's method returns pointer on any member you shouldn't forget write const before returning type example:

const float * getPosition() const{...}

segevara
  • 610
  • 1
  • 7
  • 18