Is it possible to return an object from a static method in C++ like there is in Java? I am doing this:
class MyMath {
public:
static MyObject calcSomething(void);
private:
};
And I want to do this:
int main() {
MyObject o = MyMath.calcSomething(); // error happens here
}
There are only static methods in the MyMath class, so there's no point in instantiating it. But I get this compile error:
MyMath.cpp:69: error: expected primary-expression before '.' token
What am I doing wrong? Do I have to instantiate MyMath? I would rather not, if it is possible.
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();