Is it possible to create member function in a class without using or without creating an object? If so in what scenarios can one achieve this also tell me if this concept is possible is this used in real time applications.
Is it possible to create member function in a class without using or without creating an object? If so in what scenarios can one achieve this also tell me if this concept is possible is this used in real time applications.
Hi Everyone,
This is Sriharsha congratulations for the three winners
---Harsha
I fail to understand how Harsha'a post came here... I could see he's new here... Kindly can eny of the moderators delete/move that post which is irrelevant for the discussion?
Yes. You can use static funstions for this purpose. Static functions should be used without having an instance of the class. Here's an example.
Cheers,#include <stream.h>
static const int MAX_STACK = 100;
class Stack
{
private:
static int stack[MAX_STACK];
static int top;
public:
static void push (int item) { stack[top++] = item; }
static int pop () { return stack[--top]; }
static int is_empty () { return top == 0; }
static int is_full () { return top >= MAX_STACK; }
};
main ()
{
for (srandom (time (0L)); !Stack::is_full (); Stack:: push (random ()))
;
while (!Stack::is_empty ())
cout << Stack:: pop() << "\n";
}
Kalayama
Kalayama thanks for you reply. I understood that static function is used for the query I asked.But could you tell me why we need such concept or in other words in what scenarios would we use these.
Well, I personally have used this feature to handle exception in multi-threaded programs.
There are a number of other possible usages for static functions. (I remember answering the same question in Geek interview, may be in Q&A or FAQ section. Search for it, might have written more there)
PS: Too little time mate, will post a detailed reply soon
[COLOR="Blue"][SIZE="2"]"If you are not living on the edge of your life, you are wasting space"[/SIZE][/COLOR]
Someone says "Impossible is nothing". The man next him says "Let me see you licking your elbow tip!"