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
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With