Monday, October 15, 2007

Inside the c++ object model (4)


C++ supports three flavors of member functions: static, nonstatic, and virtual.

If normalize() is a virtual member function, the call
ptr->normalize(); would be internally transformed to
(*ptr->vptr[1])(ptr); where
  • vptr represents the internally generated virtual table pointer inserted within each object whose class declares or inherits one or more virtual function.
  • 1 is the index into the virtual table slot associated with normalize();
  • ptr in its second occurrence represents the this pointer.
Static member function:
The primary characteristic of a static member functions is that it is without a this pointer.
  • it cannot directly access that nonstatic members of its class
  • it cannot be declared const, volatile, or virtual
  • it does not need to be invoked through an object of tis class.
virtual member function:
implementation model: every class has a virtual table, which contains the addresses of the set of virtual functions. Every object has a vptr, which point to the virtual table

C++ polymorphism- from a public base class pointer (reference), address the derived class object.
The only certain way of identifying a class intended to support polymorphism is the presentce of one or more virtual functions.
Every class only has one virtual table. Each table holds the address of all the vitual function instances 'active', which include:
  • an instance defined within the class for overriding case
  • an instance inherited from the base class
  • a pure_virtual_called() ..?
Pointer-to-member functions:
double // return type
( Point:: * // class name, the member function is inside
coord ) // name of the pointer
double ( Point:: *coord ) () = & Point::x; //define and initialize a pointer
coord = &Point::y; // assign a value

No comments:

Post a Comment