Вопрос

I have a question related with the example below:

Class A{virtual foo(};virtual g()}; 
Class B: public A {virtual foo();virtual g()};
B::foo(){A::foo()};
A::foo(){g()};

When I call B::foo(), it will use B::g() not A::g(), how to explain it, is it because of the 'this' pointer always points to the current object? Thanks a lot!

Это было полезно?

Решение

In B::foo() you are calling A::foo(), passing it this pointer which points to object of type B.

Inside A::foo() you're calling this->g() which is polymorphic and it will call B::g(), because type of this pointer inside A::foo() is B.

Другие советы

Since g() is virtual, it is resolved at runtime. At runtime, this pointer is pointing to B's object and hence g() of B is called

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top