Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring C++ member function as static const yields errors

I have the following class interface:

class Test
{
public: 
    Test();
    static void fun() const;

private:
    int x;
    static int i;
};

Test.cpp contains fun()'s implementation:

void Test::fun() const
{
   cout<<"hello";
}

it is giving me errors... modifiers not allowed on static member functions

What does the error mean? I want to know the reason why I am not able to create a function which is static as well as const.

like image 973
teacher Avatar asked Aug 30 '11 23:08

teacher


2 Answers

void fun() const;

means that fun can be applied to const objects (as well as non const). Without the const modifier, it can only be applied on non const object.

Static functions by definition need no object.

like image 81
George Kastrinis Avatar answered Sep 30 '22 14:09

George Kastrinis


A member function being const means that the other non-const members of the class instance can't be called.

A free function isn't a member function, so it's not associated as to a class or class instance, so it can't be const as there is no member.

A static function is a free function that have it's name scoped inside a class name, making it always relative to a type, but not associated to an instance of that type, so there is still no member to get access to.

In those two last cases, there is no point in having const access, as there is no member to access to.

like image 28
Klaim Avatar answered Sep 30 '22 15:09

Klaim