APerson
APerson

Reputation: 8422

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.

Upvotes: 0

Views: 658

Answers (3)

j_v_wow_d
j_v_wow_d

Reputation: 511

Friend functions do not have access to this, which is only accessible for functions that are members of the class. this references a specific instance of that class, and by nature friend functions, though defined in the class file, are not member functions.

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 595827

The problem is your friend statement. It is not declaring a member of the class, it is declaring an outside non-member function that is to be a friend of the class. A non-member function cannot be declared as const. That is what the first compiler error is complaining about. The second compiler error is due to the fact that you are declaring a friendship and not a member, so the syntax of the definition for the member's body is invalid - there is no member declared, so you cannot define the member's body.

You are trying to create a member method, so you need to remove the friend specifier (there is no reason to declare members as friends):

class Foo {

public:
    int getX() const;

private:
    int x;
};

Upvotes: 1

jamesdlin
jamesdlin

Reputation: 89965

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.

Upvotes: 2

Related Questions