Alex Rivera | Logout

How to call C++ static method

Asked 2009-07-30T19:38:26.667
35

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.

Edit
Report

1 Answer

12

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.

answered 2009-07-30T19:40:29.847

Your Answer