static functions constant static member functions - c++

I want to ask a simple question
Like for example in my private member I have declared static member.
static int id;
and in the public I have used getter function for this id
static int getID() const;
The compilor is giving me an error but when I dont use const it does not give any error, because this is only getter it should be constant, please tell me the reasons.

This is a static function which cannot be const, because it doesn't act on any particular instance of class. This means such function has no this pointer (passed implicitly as hidden argument) to any particular instance. You should write
static int id;
static int getID();
It is also possible to make this function non static
int getID() const;
however such a function in general should be static, as long as it doesn't need access to specific object's representation.

Related

I wrote such a member function in Clion, why does the IDE prompt to add const here? [duplicate]

i'm trying to understand class getters and setters functions...
My question is:
If i design a function that just only get a state from its class (a "getter" function), why mark it as "const member function"?
I mean, why use a const member function if my function is designed to not change any proprieties of its class?
i don't understand please :(
for example:
int GetValue() {return a_private_variable;}
and
int GetValue() const {return a_private_variable;}
what is the real difference?
When you declare a member function as const, like in
int GetValue() const;
then you tell the compiler that it will not modify anything in the object.
That also means you can call the member function on constant object. If you don't have the const modifier then you can't call it on an object that has been defined as const. You can still call const member functions on non-constant objects.
Also note that the const modifier is part of the member function signature, which means you can overload it with a non-const function. That is you can have
int GetValue() const;
int GetValue();
in the same class.
const can show up in three different places in C++.
Example 1:
const Object obj1;
obj1 is a const object. Meaning that you can not change anything on this object. This object can only call const member functions like
int GetValue() const {return a_private_variable;}
Example 2:
int myMethod() const {//do something}
This is a const method. It would be a const member function if it is declared inside of a class. These are the types of methods that const variables can call.
Example 3:
int myMethod(const Object &x) {//do something with x}
This is a method that takes a const parameter. This means that the logic inside myMethod is not allowed to change anything to do with x. Also note the parameter is being passed by reference not by copy. I like to think of this as a read only type of method.
When you are developing software that will be used by others; it is a good idea to not let them break things they don't know they should not break. In this case you can constrain variables, methods, and parameters to be const to guaranteed that the contract is upheld. I tried to summarize the main ideas I learned in college, but there are many resources online around const in C++. Check out this link if you would like to know more. Also it is possible that I remembered somethings incorrectly as I have not been in the C/C++ realm for a while.
A const instance of a class can only call const functions.
Having a const instance of a class is useful for making your programs more stable since then you can't modify the instance by accident.
In your case the functions do exactly the same thing, but it doesn't have to be that way.

Sorting vector of objects with respect to std::variant field [duplicate]

i'm trying to understand class getters and setters functions...
My question is:
If i design a function that just only get a state from its class (a "getter" function), why mark it as "const member function"?
I mean, why use a const member function if my function is designed to not change any proprieties of its class?
i don't understand please :(
for example:
int GetValue() {return a_private_variable;}
and
int GetValue() const {return a_private_variable;}
what is the real difference?
When you declare a member function as const, like in
int GetValue() const;
then you tell the compiler that it will not modify anything in the object.
That also means you can call the member function on constant object. If you don't have the const modifier then you can't call it on an object that has been defined as const. You can still call const member functions on non-constant objects.
Also note that the const modifier is part of the member function signature, which means you can overload it with a non-const function. That is you can have
int GetValue() const;
int GetValue();
in the same class.
const can show up in three different places in C++.
Example 1:
const Object obj1;
obj1 is a const object. Meaning that you can not change anything on this object. This object can only call const member functions like
int GetValue() const {return a_private_variable;}
Example 2:
int myMethod() const {//do something}
This is a const method. It would be a const member function if it is declared inside of a class. These are the types of methods that const variables can call.
Example 3:
int myMethod(const Object &x) {//do something with x}
This is a method that takes a const parameter. This means that the logic inside myMethod is not allowed to change anything to do with x. Also note the parameter is being passed by reference not by copy. I like to think of this as a read only type of method.
When you are developing software that will be used by others; it is a good idea to not let them break things they don't know they should not break. In this case you can constrain variables, methods, and parameters to be const to guaranteed that the contract is upheld. I tried to summarize the main ideas I learned in college, but there are many resources online around const in C++. Check out this link if you would like to know more. Also it is possible that I remembered somethings incorrectly as I have not been in the C/C++ realm for a while.
A const instance of a class can only call const functions.
Having a const instance of a class is useful for making your programs more stable since then you can't modify the instance by accident.
In your case the functions do exactly the same thing, but it doesn't have to be that way.

having error while compiling with static method

Stated on my title, trying to compile my file with a static method inside my code.
My computeCivIndex() is trying to get 5 inputs from user and do a calculation and return the float value back.
this.sunType is for java syntax, but for V++ what should I use to link them together if both are the same name?
I have getter and setter methods in my code and also 2 constructors which is too lengthy to be posted.
This is my error:
test.cpp:159: error: cannot declare member function ‘static float LocationData::computeCivIndex(std::string, int, int, float, float)’ to have static linkage
test.cpp: In static member function ‘static float LocationData::computeCivIndex(std::string, int, int, float, float)’:
test.cpp:161: error: ‘this’ is unavailable for static member functions
The code:
class LocationData
{
private:
string sunType;
int noOfEarthLikePlanets;
int noOfEarthLikeMoons;
float aveParticulateDensity;
float avePlasmaDensity;
public:
static float computeCivIndex(string,int,int,float,float);
};
static float LocationData::computeCivIndex(string sunType, int noOfEarthLikePlanets,int noOfEarthLikemoons, float aveParticulateDensity, float avePlasmaDensity)
{
this.sunType = sunType;
this.noOfEarthLikePlanets = noOfEarthLikePlanets;
this.noOfEarthLikeMoons = noOfEarthLikeMoons;
this.aveParticulateDensity = aveParticulateDensity;
this.avePlasmaDensity = avePlasmaDensity;
if(sunType == "Type O")
//and more for computation
}
static declaration defers from static implementation. Static implementation means that your function symbol is only available within the file where it is implemented.
Simply remove the static before the function implementation. Futhermore, static function are class function, you can't access non-static members of the class in them. Those are meant to be used without object instance, an so, there is no instance variables.
float LocationData::computeCivIndex(string sunType, int noOfEarthLikePlanets,int noOfEarthLikemoons, float aveParticulateDensity, float avePlasmaDensity)
{
}
The compiler error seems reasonably clear to me:
error: ‘this’ is unavailable for static member functions
Basically, because the member is static, it doesn't execute within the context of a particular instance of the type - so using this within the method is meaningless. You do try to use this, hence the error.
From the MSDN documentation for static:
When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.
It sounds like you just don't want to declare the member as being static.
(As an aside, I don't like the description saying it's "shared by all instances of the class" - I prefer the idea that it's not specific to any particular instance of the class. There don't have to be any instances created, at all.)

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.
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.
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.
Static functions work without an instance, whereas const guarantees that the function will not change the instance (even though it requires an instance).
It may be easier to understand if you see the translated code:
static void fun();
at the end of the day is translated to a function that takes no argument, namely
void fun();
For the other example,
void fun() const;
at the end of the day is translated to a function of the form
fun(const Test& self)
Thus, static void fun() const has two contradictory meanings.
BTW: This translation occurs for all member functions (const or not)
i answered this a few hours ago here: Why we need to put const at end of function header but static at first?
(SO system is not happy with my response. automatically converted to comment)
Perhaps it would help to have a simple code example.
class Foo {
public:
static void static_function();
void const_function() const;
};
// Use of static function:
Foo::static_function();
// Use of const function:
Foo f;
f.const_function();
The key difference between the two is that the const function is a member function -- that is, it is invoked on instances of the Foo class. That means you first need to instantiate an object of type Foo, and then that object acts as the receiver of the call to const_function. The const itself means that you won't modify the state of the object which is the receiver of that function call.
On the other hand, a static function is essentially a free function, where you can call it without a receiving object. Outside the scope of the class where it's defined, however, you'll need to qualify it using the class name: Foo::static_function.
This is why it doesn't make sense to have a function which is both static and const, as they're used in entirely different contexts. There's no need to worry about modifying the state of any object when invoking a static function because there is no receiving object -- it is simply invoked like a free function.
Because a static const function of a class does not make sense. const means that a thing (object/variable) stays the same. Static means that a thing object etc stays the same in that context.

const member functions can call const member functions only?

Do const member functions call only const member functions?
class Transmitter{
const static string msg;
mutable int size;
public:
void xmit() const{
size = compute();
cout<<msg;
}
private:
int compute() const{return 5;}
};
string const Transmitter::msg = "beep";
int main(){
Transmitter t;
t.xmit();
return EXIT_SUCCESS;
}
If i dont make compute() a const, then the compiler complains.
Is it because since a const member function is not allowed to modify members, it wont allow
any calls to non-consts since it would mean that the const member function would be 'indirectly' modifying the data members?
Is it because since a const member function is not allowed to modify members, it wont allow any calls to non-consts since it would mean that the const member function would be 'indirectly' modifying the data members?
Yes.
Yes: const member functions only see the const version of the class, which means the compiler will not find any non-const members (data or functions) inside a const member function.
This effect propagates to const objects (instances) of the class, where only const members are accessible.
When applied correctly, const will allow for the programmer to check his use of the class and make sure no unwanted changes are made to any objects that shouldn't be changed.
Yes. When you call 'xmit()', its 'this' pointer will be const, meaning you can't then call a non-const method from there, hence 'compute()' must be const
As others have said; yes.
If there is a particular reason you want compute to be non const, for example if it uses some local cache to store calculations, then you can still call it from other functions that are declared const by declaring a const version
private:
int compute() const{return ( const_cast<Transmitter*>(this)->compute());}
int compute() {return 5;}
Your assertion and your analysis are both correct.