Is it possible to invoke a c++ class method without first creating a class instance?
Suppose we have the following code:
// just an example
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass();
~MyClass();
int MyMethod(int *a, int *b);
};
// just a dummy method
int MyClass::MyMethod(int *a, int *b){;
return a[0] - b[0];
}
Here’s another example:
#include <iostream>
using namespace std;
class MyClassAnother {
public:
MyClassAnother();
~MyClassAnother();
int MyMethod(int *a, int *b);
};
// just a dummy method
int MyClassAnother::MyMethod(int *a, int *b){;
return a[0] + b[0];
}
As we can see, in the above examples, both classes have no internal variables and use dummy constructors / destructors; Their sole purpose is to expose one public method, MyMethod(..). Here’s my question: assume there are 100 such classes in the file (all with different class names, but with an identical structure — one public method having the same prototype — MyMethod(..).
Is there a way to invoke the MyMethod(..) method calls of each one of the classes without first creating a class instance for each?
Use the keyword ‘static’ to declare the method:
Then you can call the method without an instance like so:
‘static’ methods are functions which only use the class as a namespace, and do not require an instance.