简体   繁体   中英

Resolving of vptr

class base {
public:
    virtual void fn(){}
};

class der : public base {};

I know that compiler provides a member call VPTR in class which is initialised with the exact VTABLE at run time by constructor. I have 2 questions

1) Which class holds the VPTR. or all the class is having seperate VPTR.

2) When executing statement der d; how VPTR is being resolved at run time?

vtable is created for the class that contains virtual function and for the classes derived from it.It means in your program vtable will be created for base class and der class.Each of these vtables would contain the address of virtual function void fn() .Now note that der class doesn't contain the definition of void fn() ,hence its vtable contains the address of base class's void fn() function.Thus if u make a call like d.fn(); the void fn() function of base class would get executed.

Note: a virtual table and a virtual pointer are implementation details, though all the C++ compilers I know use them, they are not mandated by the Standard, only the results are.

To answer your specific question: each instance of a class with virtual methods (either its own, or inherited ones) or a class with (somewhere) a virtual inheritance relationship will need at least one virtual-pointer.

There can be several (when virtual inheritance or multi-inheritance are involved).

In your example, a single virtual pointer is sufficient. However it does not make sense to speak of it as being part of a class . The virtual pointer is part of the instance (object), and lives outsides the classes rules because those apply to the language, and the virtual pointer is an implementation mechanism.

1) which class holds the VPTR. or all the class is having seperate VPTR.

Every class object has its own vptr if the class is polymorphic (ie contains virtual function or has virtual inheritance.) In this case both the classes has virtual function.

2) when executing statement der d; how VPTR is resolve at run time?

You are just declaring the object of der . But even if you call a function then in this case the call to any function is resolved at compile time . Virtual function resolution comes into picture only when the function is called with pointer/reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM