I have tried this:
class A{
void fun()
{
cout<<"Hello World";
}
};
int main()
{
A* obj;
obj->fun();
}
It prints "Hello World". but I havent allocated any memory.
I have tried this:
class A{
void fun()
{
cout<<"Hello World";
}
};
int main()
{
A* obj;
obj->fun();
}
It prints "Hello World". but I havent allocated any memory.
The code in question has undefined behavior, using an indeterminate value for the pointer.
It might crash, or do anything, including that it might work.
If a member function doesn't need an instance, make it a static
member function; then you can call it like A::fun()
.
It is an undefined behavior since the pointer has an undefined value. Even if you try to assign the value 0 to obj
then also the obj->fun()
will be undefined and will result in undefined behavior.
The C++ standard says:
If the object to which the lvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior.
You can do it this way --
#include <stdio.h>
class A{
public:
static void fun()
{
printf("Hello World\n");
}
};
int main()
{
A::fun();
}
Advantage:
§9.3.1 [class.mfct.non-static]/p2:
If a non-static member function of a class
X
is called for an object that is not of typeX
, or of a type derived fromX
, the behavior is undefined.