I have a function defined in a C++ source file called spiral.cpp
, I am trying to call that function from another C++ source file called manager.cpp
. However, I am getting a compile error that says "illegal call of non-static member function".
I have had a look for the reasons for getting this compile error, and everything I've found so far seems to tell me that I need to make the function static
in its definition. However, if I do that, I then get a compile error that says that "'static' should not be used on member functions defined at file scope".
The function is defined in spiral.cpp
with the code:
int spiralItem::updateCircuitNumber(void){
...
}
It is then called in manager.cpp
with the line:
spiral::updateCircuitNumber();
Can anyone explain to me what I'm doing wrong here? Is the problem definitely to do with the function being defined/ called as static/ non- static incorrectly, or is it something else?
As mentioned in my comment, your function name makes me assume that you actually want to manipulate state of a particular spiral
instance. In this case, you would need (or at least usually use) a member function. It seems this is what you actually did. Check.
Now, in order to call this function, you need to have an instance of spiral
that you can call the function on.
spiral s;
s.updateCircuitNumber();
or (if allocated dynamically)
spiral * s = new spiral(); // better use appropriate smart_ptr but that's another story
s->updateCircuitNumber();
These calls change the state of that particular s
object. If you have another spiral
object s2
, this remains unchanged and you are free to call updateCircuitNumber()
for that instance as well as needed. Non-static member functions are also called instance functions because they operate on a particluar instance of a class.
static
functions are also referred to as class functions because they are independent of a particular instance of that class. Therefore, they may only access static members of that class, but not non-static ones (as these only exist for a particular instance which is not available). As mentioned in the other answers, the static
keyword is only added inside the class declaration. Static function can then be called as you tried with spiral::updateCircuitNumber();
.