tags:

views:

241

answers:

4

Which virtual table will be pure virtual function located? In the base class or derived class?

For example, what does the virtual table look like in each class?

class Base {

  virtual void f() =0;
  virtual void g();
}


class Derived: public Base{

  virtual void f();
  virtual void g();

}
+1  A: 

The vtable entry will be in the base class.

Why? Because you can have a base pointer type that holds a derived type object's address and still call the method on the base type's pointer variable.

Pure virtual simply tells the compiler that the derived types must provide their own implementation, and they cannot rely on the base class' implementation (if one is even specified in the base class)

Brian R. Bondy
+1  A: 

In both actually. The base class vtable will have a slot for the pure virtual function pointing to something like pure_virtual_function_called() stub that would probably abort the program, while the derived class vtable will have a pointer to the actual implementation.

Nikolai N Fetissov
+2  A: 

Each class has its own vtable. The entry for f in Base will be NULL, and the entry in Derived will be a pointer to the code for the implemented method.

Jen
Well, not really NULL. In VC++ the entry is the address of the CRT function _purecall: http://thetweaker.wordpress.com/2010/06/03/on-_purecall-and-the-overheads-of-virtual-functions/
Ofek Shilon
+7  A: 
Artem
Cool stuff indeed :)
Nikolai N Fetissov
+1 Nice - beat all guess work
Fadrian Sudaman