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?
Static method(s) are associated with the class in which they reside i.e. they are called without creating an instance of the class i.e ClassName. methodName(args). They are designed with the aim to be shared among all objects created from the same class.
We can also make class methods that can be called without having an instance. The method is then similar to a plain Python function, except that it is contained inside a class and the method name must be prefixed by the classname. Such methods are known as static methods.
C# static methods Static methods are called without an instance of the object. To call a static method, we use the name of the class and the dot operator. Static methods can only work with static member variables.
We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.
Use the keyword 'static' to declare the method:
static int MyMethod( int * a, int * b );
Then you can call the method without an instance like so:
int one = 1; int two = 2; MyClass::MyMethod( &two, &one );
'static' methods are functions which only use the class as a namespace, and do not require an instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With