Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is throwing the error the static or the const?

The following code is throwing an error message and I can't figure out what the issue is - is it the word static, or const? What am I doing wrong?

#include <iostream>
using namespace std;

class SampleClass
{
private:

    int value;
    static int counter;

public:

    SampleClass(int i)
    {
        value = i; 
        counter++;
    }

    static int countSomeClass() const
    {
        return counter;
    }

    void showValue()
    {
        cout << value << endl;
    }

};

int main()
{
    SampleClass test(50);
    test.showValue();
    test.countSomeClass();
    return 0;
}

Error message:

main.cpp:16:35: error: static member function static int SampleClass::countSomeClass() cannot have cv-qualifier
static int countSomeClass() const

like image 760
YelizavetaYR Avatar asked Oct 23 '14 14:10

YelizavetaYR


People also ask

What is the difference between static and const?

A static keyword is been used to declare a variable or a method as static. A const keyword is been used to assign a constant or a fixed value to a variable. In JavaScript, the static keyword is used with methods and classes too. In JavaScript, the const keyword is used with arrays and objects too.

Is it static const or const static?

They mean exactly the same thing. You're free to choose whichever you think is easier to read. In C, you should place static at the start, but it's not yet required.

Can a static function be const?

A static member function cannot be declared with the keywords virtual , const , volatile , or const volatile . A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared.


1 Answers

A static method cannot be marked as const: since it doesn't work on an instance, it makes no sense to specify that it cannot modify it.

(you could argue that for static methods it could have referred to static methods that cannot modify the static data associated with the class; however, this would have no use anyway, since you cannot have a const class or form a const pointer or reference to a class, as in C++ classes aren't objects)

like image 164
Matteo Italia Avatar answered Oct 08 '22 19:10

Matteo Italia