What is virtual pointer? Hi, ALL, Today I had an telephone interview and got a question: "What is virtual pointer?" I stumbled on this one, so after it was finished, I tried Google. Unfortunately, it gave me a virtual table references only.
So what is virtual pointer in plain English? How do you define it?
Thank you.
If object of that class is created then a virtual pointer (VPTR) is inserted as a data member of the class to point to VTABLE of that class. For each new object created, a new virtual pointer is inserted as a data member of that class.
A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.
cpp) into the class. There is only one VPTR for each object when using simple inheritance like this. The VPTR must be initialized to point to the starting address of the appropriate VTABLE.
The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into a derived class.
There is no such thing as a "virtual pointer."
There are a few things the interviewer might have meant:
operator->
But as far as "virtual pointer" is concerned, there's no such thing.
C++ compiler creates a hidden class member called virtual-pointer or in short vptr when there are one or more virtual functions. This vptr is a pointer that points to a table of function pointers. This table is also created by compiler and called virtual function table or vtable. Each row of the vtable is a function pointer pointing to a corresponding virtual function.
To accomplish late binding, the compiler creates this vtable table for each class that contains virtual functions and for the class derived from it. The compiler places the addresses of the virtual functions for that particular class in ‘vtable’.
When virtual function call is made through a base-class pointer, the compiler quietly inserts code to fetch the VPTR and look up the function address in the VTABLE, thus calling the right function and causing late/dynamic binding to take place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With