Oct 5, 2010 at 7:21am Oct 5, 2010 at 7:21am UTC
You ask a question I would like to know the answer too. I believe a* b='\0'; this statement is doing some assignment and construction ? How about try below instead.
a* b; //declare b as a pointer variable with no assignment and then below call f() function
b->f();
Oct 5, 2010 at 7:44am Oct 5, 2010 at 7:44am UTC
hello harsh4u89,
This a* b='\0' ;
assigns a null pointer. like null->f();
The first example doesn't crash because f() doesn't access any other member.
The second crash because 'virtual' is a kind of member.
Use static void f() {}
if you want to call that function without an object. you can't access any none static members of that class nevertheless.
Last edited on Oct 5, 2010 at 8:08am Oct 5, 2010 at 8:08am UTC
Oct 5, 2010 at 7:54am Oct 5, 2010 at 7:54am UTC
Your code works fine because f doesn't
modify access any data. When you write a member function, the actual code generated for it is equivalent to a static function that takes an extra argument, the object to operate to.
For example, the code bellow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
using namespace std;
class A
{
int n;
public :
void f()
{
cout << "Hello, World!" << endl;
}
void g()
{
cout << n << endl;
n=0;
}
};
int main()
{
A * a=0;
a->f();
//uncommenting will
//probably cause a crash
//a->g();
cin.get();
return 0;
}
is equivalent to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
using namespace std;
class A
{
int n;
public :
static void f(A * a)
{
cout << "Hello, World!" << endl;
}
static void g(A * a)
{
cout << a->n << endl;
a->n=0;
}
};
int main()
{
A * a=0;
A::f(a);
//uncommenting will
//probably cause a crash
//A::g(a);
cin.get();
return 0;
}
I believe it is now clear why f doesn't cause a problem, while g does.
EDIT: Too slow... And, yes, in the second example, the problem is the uninitialized (inexistent) virtual table.
Last edited on Oct 5, 2010 at 8:13am Oct 5, 2010 at 8:13am UTC