class Base { }
class D1 extends Base {
public:
virtualvoid D1func() {
cout<<"D1func()"<<endl;
}
}
int main() {
Base b = new D1();
b.D1func();
return 0;
}
My understanding of the virtual pointer mechanism is:-
1. Virtual table is setup for each every class at compile time.
2. Base class contain's pointer to a virtual table (which is inherited into all derived classes).
3. The base pointer is set to the correct table depending on what kind of object is created.
When we say Base *b = new D1(); the baseptr pointer is pointing to the virtual table of D1(). Virtual table of class D1 does have an entry for D1func(). Yet we cant call D1func() using base pointer b. Whats the reason for that?
I understand it doesn't make (object oriented) sense to call b.D1func() however is it possible using the table pointed to by the *baseptr (pointer to virtual table)?
Can I assume because we deal in C++ here that your code looks more like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Base { };
class D1 :public Base
{
public:
virtualvoid D1func()
{
cout<<"D1func()"<<endl;
}
};
int main() {
Base *b = new D1;
b->D1func();
return 0;
}
D1func() does not exist in Base class - Base Class has no virtual function or non-virtual function of that name - so you cannot call it - simple as that.
This is C++, please ignore the extends. The idea was to convey inheritance. Also, i don't know if this is possible but can we go through the code in the OS which does this, (i.e. going through the table, calling the function etc). Any idea where i could find this code?
The reason you can't call D1func in your program is because base has no version of it, as I recall. The point of virtuality is to differentiate static from dynamic type. Since there is no possible way base could call D1func, the behavior is not virtual and you get an error.
And I second helios, we don't use extends in C++ and neither do we intialize class objects the java way. (as in = new classnamehere(constructorargs).
There is no code in the OS that handles virtuality. Virtuals are controlled by the language, they are an inherent syntax factor. What does the OS have to do with the matter?
When the compiler sees a call to a virtual through a pointer it generates code that could call any of the valid versions based on the dynamic type of the object pointed to. It's that simple.
When the compiler sees a call to a virtual through a pointer it generates code that could call any of the valid versions based on the dynamic type of the object pointed to. It's that simple.
So this means the compiler injects code into our source code which will index the virtual table and call the correct function, whenever we make a call to a virtual function? I was just curious to know where this indexing of the virtual table and calling the correct virtual function happens.