3

I'm passing the reference of an object to a function and I used const to indicate that it's read-only method, but if I call another method inside of that method this error occur, even if I'm not passing the reference as argument.

error: passing 'const A' as 'this' argument of 'void A::hello()' discards qualifiers [-fpermissive]

error: passing 'const A' as 'this' argument of 'void A::world()' discards qualifiers [-fpermissive]

#include <iostream>

class A
{
public:
    void sayhi() const
    {
        hello();
        world();
    }

    void hello()
    {
        std::cout << "world" << std::endl;
    }

    void world()
    {
        std::cout << "world" << std::endl;
    }
};

class B
{
public:
    void receive(const A& a) {
        a.sayhi();
    }
};

class C
{
public:
    void receive(const A& a) {
        B b;
        b.receive(a);
    }
};

int main(int argc, char ** argv)
{
    A a;
    C c;
    c.receive(a);

    return 0;
}
Community
  • 1
  • 1
yayuj
  • 2,194
  • 3
  • 17
  • 29
  • 1
    what happend to *shortest* code necessary.... – Karoly Horvath Nov 17 '14 at 12:33
  • A method marked as `const` should only call `const` methods and not attempt to modify member variable (other than `mutable`). – Niall Nov 17 '14 at 12:34
  • _"...even if I'm not passing the reference as argument."_ You are passing it, because of the implicit `this` argument. – Oktalist Nov 17 '14 at 14:15
  • @Oktalist - Sorry for my ignorance, but what you mean? – yayuj Nov 17 '14 at 14:19
  • @MrAlmighty `hello(); world();` actually means `this->hello(); this->world();`. – Oktalist Nov 17 '14 at 14:20
  • @Oktalist - But where am I passing anything as reference? I don't get it. – yayuj Nov 17 '14 at 14:21
  • 1
    When `sayhi` is called via `a.sayhi()`, `this` points to the same object which `a` refers to. – Oktalist Nov 17 '14 at 14:26
  • Possible duplicate of [error: passing 'const …' as 'this' argument of '…' discards qualifiers](http://stackoverflow.com/questions/26963510/error-passing-const-as-this-argument-of-discards-qualifiers) – Bak Itzik Aug 03 '16 at 07:15

1 Answers1

10

Since sayhi() is const, then all functions it calls must also be declared const, in this case hello() and world(). Your compiler is warning you about your const-correctness.

Community
  • 1
  • 1
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    The program is ill-formed. Those aren't "warnings". – Kerrek SB Nov 17 '14 at 12:35
  • I shouldn't have used the word "warning" because I didn't mean to imply that they were compiler warnings. I meant it was.... "advising" them, I don't have a great vocabulary :) – Cory Kramer Nov 17 '14 at 12:40
  • The word you're looking for is "ill-formed", or "error" :-) In fact, the program is ill-formed even if you don't try to compile it. – Kerrek SB Nov 17 '14 at 12:44