Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call C++ static method

People also ask

How can I call static method?

A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.

How do you call a static method in Objective C?

You can call this method by his class's instance name like : MyClass *object = [[MyClass alloc] init]; [object anInstanceMethod];

Are there static methods in C?

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.

Can I call a static function from another file in C?

In C, we can declare a static function. A static function is a function which can only be used within the source file it is declared in. So as a conclusion if you need to call the function from outside you do not define the function as static .


Use :: instead of .

MyObject o = MyMath::calcSomething();

When you are calling the method without the object of the class you should use :: notation. You may also call static method via class objects or pointers to them, in this case you should use usual . or -> notation:

MyObject obj;
MyObject* p = new MyObject();

MyObject::calcSomething();
obj.calcSomething();
p->calcSomething();

What am I doing wrong?

You are simply using incorrect syntax... the :: operator (scope resolution operator) is how you would access classes or members in different namespaces:

int main() { 
    MyObject o = MyMath::calcSomething(); // correct syntax
}

Do I have to instantiate MyMath?

No.


For this case, you want MyMath::calcSomething(). The '.' syntax is for calling functions in objects. The :: syntax is for calling functions in a class or a namespace.


Call MyMath::calcSomething()


Try this way

#include <iostream>
using namespace std;
class MyMath {  
public:
    static MyMath* calcSomething(void);
private:
};
MyMath* MyMath::calcSomething()
{
    MyMath *myMathObject=new MyMath;
    return myMathObject;
}
int main()
{   
    MyMath *myMathObject=MyMath::calcSomething();
    /////Object created and returned from static function calcSomeThing   
}

Thanks