Re: Pure Virtual Function Calls

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Hallo pakis!

I am having a problem of pure virtual function call in my project.

What problems?

Can anyone explaine me the causes of pure virtual function calls other than calling a virtual function in base class?

A normal call to a member or static function of a class can be directly resolved by the compiler and linker. If the this pointer is invalid. the correct function will start to execute but the function may crash when data via the this pointer is accessed.


A virtual function uses a vtable (a table of pointers to the virtual functions), so when calling a virtual function the this pointer must be correct because the code that executes a virtual function will fetch the address for the function at the proper index of the vtable.

So calling a non-virtual function with the object pointer==NULL is possible, but calling a virtual-function with a NULL pointer usually causes a crash.

I.e.
CWnd *pWnd = NULL;
pWnd->GetSafeHwnd();
will return FALSE;
The function checks if the this pointer is false.
Calling any virtual function of CWnd will immediately crash.

--
Martin Richter [MVP] WWJD
"In C we had to code our own bugs. In C++ we can inherit them."
FAQ : http://www.mpdvc.de
Samples: http://www.codeguru.com http://www.codeproject.com
.



Relevant Pages

  • Re: c++ : a baseclass, derived classes, a list of baseclass pointers, a problem.
    ... > I overwrote the virtual function func1() in each derived class. ... > How can I execute the right function? ... > I use a pointer to the baseclass to loop trough ... You could cast to the base class and investigate the vtable pointer, ...
    (comp.programming)
  • sizeof(object) is different in ANSI and Unicode
    ... A class having no member variables and only a method sizeof ... I have the answer for this of how in works in ANSI. ... form a pointer to an empty object that is distinct from a pointer to ... For a class with virtual function, size of a virtual function is a ...
    (comp.lang.cpp)
  • Re: Why sizeof(struct) is different in C and C++ ?
    ... >> My conceptual view is a stack of base classes, ... For "ordinary" inheritance where each class inherits from exactly one immediate ... for just a single virtual function table pointer. ...
    (comp.lang.cpp)
  • Re: is it good, is it bad or plain eeevil ?
    ... > This is a virtual function call regardless of how call_vfun was called ... If sword is 'given' to player (that is pointer is passed), ... virtual method. ...
    (comp.lang.cpp)
  • Re: Would a static_cast be better style here?
    ... >> And of course to convert from a derived pointer type to a base pointer ... > pointer, then you are correct, there is no need to cast. ... For a virtual function the scope resolution operator is the only way. ...
    (comp.lang.cpp)