Wednesday, November 8, 2006

C++: I am sure that vptr is stored as a first member of the object !

No, you're wrong. You need to read on...

Eligibility: You should know what vptr stands for and what are its functions, and you should have basic familiarity with the C++ language.


What does 'The C++ Standard' say?

The C++ Standard is noncommittal about it. Because the standard describes C++ Language and not it's implementation.

The first implementation of C++ (by Bjarne Stroustrup) has vptr as the last member of the object/sub-object. But the Microsoft Compiler as some others have it as the first member. What are the consequences of it's positioning within the object? Lets see...


The C language portability

One current topic of debate within the C++ community concerns where best to locate the vptr within the class object. In the original cfront implementation, it was placed at the end of the class object in order to support the following inheritance pattern, shown in the figure below:

struct no_virts {
    int d1, d2;
};


class has_virts: public no_virts {
    public:
        virtual void foo();
        // ...
    private:
        int d3;
};

no_virts *p = new has_virts;

Placing the vptr at the end of the class object preserves the object layout of the base class C struct, thus permitting it's use within C code. This inheritance idiom is believed by many to have been more common when C++ was first introduced than currently.

Subsequent to release 2.0, with its addition of support for multiple inheritance and abstract base classes, and the general rise in popularity of the OO paradigm, some implementations began placing the vptr at the start of the class object.

Placing the vptr at the start of the class is more efficient in supporting some virtual function invocations through pointer to class members under multiple inheritance. Otherwise, not only must the offset to the start of the class be made available at runtime, but also the offset to the location of the vptr of that class must be made available. The trade-off, however, is a loss in C language interoperability. How significant a loss? What percentage of programs derive polymorphic class from a C-language struct? There are currently no empirical numbers to support either position.

No comments: