Search code examples
c++constantsmember-functionsfunction-qualifier

Why can't I mark this member function as const?


When I try to compile this short program:

#include <iostream>

class Foo {

public:
    friend int getX() const;

private:
    int x;
};

int Foo::getX() const { return this->x; }

int main() {
    Foo foo;
    std::cout << foo.getX() << std::endl;
}

I get these errors:

C:\>gcc test.cpp
test.cpp:6:23: error: non-member function 'int getX()' cannot have cv-qualifier
     friend int getX() const;
                       ^
test.cpp:12:17: error: no 'int Foo::getX() const' member function declared in cl
ass 'Foo'
 int Foo::getX() const { return this->x; }
                 ^
test.cpp: In function 'int main()':
test.cpp:16:22: error: 'class Foo' has no member named 'getX'
     std::cout << foo.getX() << std::endl;
                      ^

Why can't I mark getX() as const here? It doesn't modify Foo's state or anything, so I should be able to do so.


Solution

  • You're declaring a function with both friend and const. It doesn't make sense to have both together: friend isn't meaningful for member functions because member functions already have access to the class's privates. const isn't meaningful for non-member functions because there's no inherent object that they'd promise not to modify.