Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke a c++ class method without a class instance?

Tags:

c++

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?

like image 704
user58925 Avatar asked May 04 '12 03:05

user58925


People also ask

Can you call class method without creating an instance?

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.

How do you use class method without instance?

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.

How do you call a class method without creating an object in C#?

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.

How do you call a class method without creating the object of the class?

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.


Video Answer


1 Answers

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.

like image 120
Greyson Avatar answered Oct 06 '22 08:10

Greyson