Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Java static methods in C++

Tags:

c++

I'm trying to create a method in a C++ class that can be called without creating an instance of the class (like a static method in Java), but I keep running into this error: error: expected unqualified-id before ‘.’ token

Here's the .cpp file I'm trying to compile:

using namespace std;
#include <iostream>

class Method {
    public:
    void printStuff(void) {
        cout << "hahaha!";
    }
};

int main(void){
    Method.printStuff(); // this doesn't work as expected!
    return 0;
}
like image 931
Anderson Green Avatar asked Sep 08 '12 19:09

Anderson Green


People also ask

What is static method 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.

Is static is same in Java and C?

The static data members are basically same in Java and C++. The static data members are the property of the class, and it is shared to all of the objects.

What is the alternative to static in Java?

You can use the full power of inheritance and overriding since your methods are no longer static. You can use the constructor to do any initialisation, including associating SQL with the table (SQL that your methods can use later). This should make all your problems above go away, or at least get much simpler.

What is another name for static method?

A static method in Java (also called class method) is a method that belongs to the class and not the instance. Therefore, you can invoke the method through the class instead of creating an instance first and calling the method on that instance.


1 Answers

In C++ it's

Method::printStuff();

and you have to declare the method as static.

class Method{
    public:
    static void printStuff(void){
        cout << "hahaha!";
    }
};

:: is called the scope resolution operator. You can call the method with . if it's on a class instance, but the instance is not required (it being static and all...).

like image 100
Luchian Grigore Avatar answered Oct 14 '22 16:10

Luchian Grigore