Hacker News new | ask | show | jobs
by ryao 300 days ago
Let’s say I have ClassA::Foobar() and ClassB::Foobar(), and ClassB inherits from ClassA. Now let’s say I want to use ClassA::Foobar(), and I access it from the object because this pointer is in the vtable and the object is of type ClassB. Now ClassB::Foobar() executed, which is wrong. This is why static functions are not put into vtables. What Linux is doing is not a vtable, even if it shares similarities. Perhaps you would understand this if I said all thumbs are fingers, but not all fingers are thumbs.
1 comments

That's a very good example.

When I invoke object->Foobar() I want to invoke the appropriate method for this object, from whatever class that might be. This is exactly what's happening in the kernel here.

When I actually intend to call the method from ClassA, I would either call something like object->base->Foobar() or ClassA->Foobar(object). Note how this is the very example that you are replying to: https://news.ycombinator.com/user?id=1718627440

You don’t implement calls to static member functions by putting them into a vtable, which is one of many reasons why this is not a vtable. The proper way to implement static functions is through static dispatch.
> You don’t implement calls to static member functions by putting them into a vtable

Yes, you claimed it is like a static member function, I don't think it can be.

> The proper way to implement static functions is through static dispatch

Yes, but we are talking about dynamic dispatch here.

To quote your earlier comment:

> which is most unlike a vtable since static member functions are never in vtables

You conclude it isn't a vtable, I conclude, it's not a static member function, because it uses dynamic dispatch.

I don't think we actually disagree on how and when to use static and dynamic dispatch.

If you leave out the this pointer, it is the equivalent of putting a function pointer to a global function (or a static member function) into the structure. This is not how OOP works.

Omitting the this pointer also breaks inheritance, since hypothetical child classes would not be able to override the definition while using the this pointer. Having to edit the parent class to be able to do that is not how OOP works.

This is not OOP nor is it intended to be.

> If you leave out the this pointer, it is the equivalent of putting a function pointer to a global function (or a static member function) into the structure.

No it is not. Unless you can show me a virtual overridden static member function.

> since hypothetical child classes would not be able to override the definition while using the this pointer

Yes! That's the entire idea here. The non-hypothetical, but indeed existing, child classes are not able to access the object. This is to prescribe potential behaviour for child implementations.