View Full Version: QUIZ

C++ Learning Community > C++ Tips > QUIZ


Title: QUIZ
Description: Will this work


myork - May 20, 2005 02:50 PM (GMT)
Here is somthing interesting that just came up:

CODE


class MyClass
{
 public:
   void doSomeWork();
};

/*
* Definition of doSomeWork() removed to make it a puzzle
*/


int main(int argc,char* argv[])
{
   MyClass*    x = NULL;

   x->doSomeWork();

   return(0);
}


The above code compiles. no surprise.
But it also runs and produce output (A bit of a surprise).
Can anybody tell me how it would work.


PS doSomeWork() is not a static member.
PPS. This is probably implementation specific behavior but worked correctly on g++ and MS cl compiler (The one shipped with dev Studio).

C-Man - May 20, 2005 03:41 PM (GMT)
it works because it's not a virtual function
it's a normal function that gets the class pointer passed as the first hidden argument
( NULL in this case ) and if the function doesn't do anything with the class
the argument is simply not used and ignored
making it virtual will make it crash

try doing this

void MyClass::doSomeWork ()
{
std::cout << (unsigned)this << '\n' ;
}

this should print 0 it shouldn't be implementation specific either

dr voodoo - May 20, 2005 04:52 PM (GMT)
But it's not standard conform as the standard requests that the "this" pointer is dereferenced when a member function is called, even though in some situations nearly no compiler does this.

:codeblks:

@myork the code is sure to work on common compilers because:
  • There are no virtual functions which need access to the vtable.
  • There are no data members which could be accessed.
This means that the "this" pointer will not be dereferenced.

FrozenKnight - May 22, 2005 07:20 PM (GMT)
All classes have a hidden pointer which points to the strict like variable table however for the constants (like functions) it references the address of the function in memory then calls that function. I know this doesn’t look right but you have to consider that classes can be dynamically created and you can't just copy the function from nowhere into a dynamic variable. So a very simple optimization is to call the function directly and as long as no class variables are referenced there should be no problem with the code running. (I assume)




Hosted for free by InvisionFree