Is there a way to call a non static class member method from another method that is contained within the main class in c++? If so, what would the code look like?
Problem is, I can't declare this specfic method as static, because it uses other methods within the same class that then don't work if I make the one static.
I'm trying to use:
MyClass::myClassMethod();
from a method within the main class, but it gives me the error: a non static member reference must be relative to a specific object.
To clarify, myClassMethod() uses other methods within MyClass like:
void myClassMethod() {
...
anotherClassMethod();
}
so if I were to make myClassMethod static it would interfere with calling anotherClassMethod().
What is the deal with calling non-static member function from a static member function?
Every non static member function is passed an this pointer implicitly in addition to the parameters you pass, the pointer passed is then dereferenced to refer class object members However static functions are not passed with the implicit thispointer and hence one cannot call any non static member function inside a static member function because there is no this to do so.
What is the solution, If you want to do it anyways?
You will need some mechanism to get the pointer to the object inside the static method and then you can call the member function using that pointer.
How to do that?
You will have to store the pointer to class object globally, or pass it as an instance in one of the function arguments to the static method.
However, both of above are workarounds, the important thing to note here is If you feel the need of calling a non static member function through a static member function then there is something wrong in your design.
On Second thoughts maybe I mis-read your Question before, Probably, Your question is:
How to call a non-static member function of a class from main?
You need a instance of the class to call non-static member functions.
So simply,
MyClass obj;
obj.myClassMethod();
And calling any other member function from within myClassMethod() would simply be:
void myClassMethod()
{
//...
anyOtherMyClassNonStaticMemberFunction();
//...
}
A static method is one that doesn't run on any particular object. It's a lot like a standalone function outside of a class, except that it's allowed to access private members in its class.
If you anotherClassMethod() is non-static, that means it has to be called on a specific object, an instance of the class. Because it's called on an object, it can access data stored in that object (non-static member variables). If myClassMethod() is static and you implement it as
void MyClass::myClassMethod() {
anotherClassMethod();
}
That won't work because anotherClassMethod() expects to be called on a specific object, but myClassMethod() doesn't have one. But if you know what object you want to call it on, you can do it as an ordinary method call on an object:
void MyClass::myClassMethod(MyClass &object) {
object.anotherClassMethod();
}
The object doesn't have to be passed in as an argument; it could be a static member variable in the class, for example:
class MyClass {
private:
static MyClass theInstance;
// ...
};
void MyClass::myClassMethod() {
theInstance.anotherClassMethod();
}
Ultimately, the question you need to ask yourself is: why is myClassMethod() static, and why is anotherClassMethod() non-static? Take a step back, think about what myClassMethod() is supposed to do. Does it make sense to call it when you don't have an instance to work with? If so, why does it need to call a method that expects to work with an instance?
The only way to call a non static method of a class is through an instance of that class. So you would need something like this...
MyClass myClass;
myClass.myClassMethod();
I think that maybe you could use the singleton pattern, keep a instance of the class in global. like a utility class.
Related
Let:
class CLASS{
void foo() {};
static void staticFoo() { foo(); }
};
Why would calling a nonstatic method from a static one be a problem? How do I go around this?
Judging by your question, it appears that you are not very familiar with object oriented programming. Writing C++ classes and not knowing object oriented programming is not the best idea. It's also not something we can sum up in a StackOverflow answer. It's best if you search for this topic and learn at least the basics before continuing. It actually would take less time that you'd imagine to get familiar with the basics.
This MIT class's presentation on object oriented programming is decent. Object oriented programming in C++
But to answer your question: why can't we call up a non-static method from a static method. Well when you define a C++ class, you're describing the model, or blueprint for making instances of something. For example, you could define a class Animal like this:
class Animal {
public:
void set_name(std::string name) { this->name_ = name; }
const std::string& get_name() const { return this->name_; }
private:
std::string name_;
};
We obviously have methods to set and get the name of this Animal class. Note that much like in the real world, we don't just name the abstract idea of animals, we'd name our own pet or some known specific animal, that happens to be one instance of an animal. This might receive criticism but you can kinda think of it as the difference between dog and the dog. The latter is a specific dog that all involved parties are aware of. That's why methods set_name and get_name need to know which animal you're talking about.
Consider this:
Animal my_dog;
my_dog.set_name("stripes");
Animal my_cat;
my_cat.set_name("katz");
The method set_name updates the name of my_dog and my_cat. We had to tell the set_name which instance we're talking about. Methods like these are instance methods, you can have a pointer to yourself which in C++ is designated by this. That's how you can update attributes about different instances. A static method doesn't receive this context and therefor won't be able to call instance methods unless of course it has access to one of these instances. For example:
static void print_animal(const Animal& animal) {
std::cout << animal.get_name() << std::endl;
}
After all of this, hopefully it makes sense why we can't just call Animal::set_name.
Why can't a nonstatic method be called from a static one?
A non-static member function can be called from a static member function.
Why would calling a nonstatic method from a static one be a problem?
It's not a problem. The problem is that you've not invoked the non-static member function on an object. Non-static member functions cannot be invoked without an object argument.
The syntaxes to invoke a non-static member function are following:
instance.mem_fun(arguments);
pointer->mem_fun(arguments);
Non-static member functions are special in that they can invoke other non-static member functions without explicit instance argument. The argument is implicitly this. Static member functions don't have this, and the exception doesn't apply to them.
How do I go around this?
Use one of the syntaxes shown above. You need to consider what instance you intend to use as the object argument of the non-static member function.
but why couldn't foo be called statically ...
Because foo is a non-static member function. Non-static member functions cannot be called statically.
... if the call is made from a static function?
Where the function is called from has no effect on whether it can be called statically.
I was reading before that static member functions of a class is similar to a global function. But this should depend on whether or not the static member function is public/private right?
For example:
class A
{
private:
static void aFunc();
};
int main()
{
A::aFunc();
}
In this case I wouldn't be able to call the static member function inside main() correct? If I instead had made it public, I can call it, just like a global function?
Yes, it does depend on the access modifier. If the function is public, then it is somewhat similar to a global function, but unlike a global function it has access to class members and has to be called with the class scope (prefixed with A:: in your example), to mention just a couple of differences.
BTW, when you call it in main(), you should just have
A::aFunc()
No need to stick void in there.
Yes, a static member function is similar to a non-member function in that you do not need to call it for an object of associated class type, but it obeys the usual class member access rules like a non-static member function.
In this case, you are correct to suggest that A::aFunc is inaccessible from main. However, your calling syntax is incorrect. You do not need to include the return type:
A::aFunc();
I have a class A in which I have a static member function passName
int A::passName()
{
.... // skip some code
std::string name = ...; // result from codes above
assign(); // this is a static member function in class A
pointerA->passMethodName(name); // pointerA is a class-A static member variable, but of type
// class-B, passMethodName is a class-B non-static member function.
}
The assign function is:
void A::assign(){
pointerA = tempPointerA;
}
Explanation: tempPointerA is a value that is generated during the running process. It is a non-static private class-A member which will be initialized everytime a new object of class A is constructed. But I know in static function I can only use static member directly, so I need to make sure that pointerA is static member. So is assign() function feasible (Or I would rather say, is the whole working principle shown here feasible)?
Thanks for your idea!
No. A static member function can only operate on static variables or call other static functions. (or namespace-scope functions, which are more or less the same as static functions).
ยง9.4.1 [class.static.mfct]
A static member function does not have a this pointer.
So there is no way to access a non-static member variable within a static function.
If you really need assign to remain static, then what you should do is to refactor yourassign()function to accept a variable of typetempPointerA`, and then pass your desired variable in.
int A::passName(B* _in)
{
std::string name = ...; // result from code above
assign(_in); // this is a static member function in class A
_in->passMethodName(name);
}
Otherwise I recommend that you not make it static at all.
Assigning the value will work, but you need to do it from a non-static method (to have access to tempPointerA) or pass the pointer as paramter to the static method. You can access static members from non-static functions (but not the other way around).
What you should pay attention is ownership and destruction. Since you assign the value to a static member the instance can't own the value anymore. Otherwise when the instance is destroyed the static member points to garbage data and you get errors. Also since the static member is never destroyed, your value may leak resources (think DB connection that's never closed).
Also if you are in multi-threaded environment consider if it's possible that multiple threads will attempt to set the value of the static member. You may have the add synchronization. You can also run into race conditions if multiple threads try to initialize the value at the same time.
There is one rule: static functions can't access non-static members and function of the same class without an object. there is no opposite rule. it is because you don't have a this pointer.
You still can declare an object of the same class in the static function and use it's all members, or use any static member.
Therefore from non-static function you can access static functions and members.
If pointerA is static you can access it all. not only to it's static members and functions.
I'm reading sample code from an SDK, and I see this:
PXCSenseManager *senseManager = PXCSenseManager::CreateInstance();
Does this mean that CreateInstance() is a method in the PXCSenseManager class and that it is called?
Yup, CreateInstance() is a public static member function of class PXCSenseManager.
It means that the CreateInstance function in the namespace PXCSenseManager is being called. From the beginning of that line one can see that PXCSenseManager is actually some class. The nature of a function that creates instances and the way it is called with an explicit namespace makes it extremely likely that CreateInstance is a static member function of the PXCSenseManager class, but if this line of code comes from within a non-static member function there is a theoretical possible that CreateInstance is a non-static member function.
I am getting an error when I call one static function of a class in to any other function (means by non-class function), then it is giving following error:
undefined reference to function name_function.
Can any one tell me why this is happing?
Basic C++: A non-static member function assumes that it has access to an object of the class type (it can refer to the member variables directly and the "this" pointer points to the object).
This means that you can't call a non-static member function unless you have an object of that type. In a static member function, you don't.
(I'm not 100% sure this is an answer to your question, as it's not clean from your explanation if you tried to call a non-static function from a static one, or vise versa.)
Are you prepending the class name before the function name?
so, if you have:
class MyClass
{
...
public static function name_function() { ... }
...
}
you need to call this function like this:
MyClass::name_function();