If an overridden C ++ function calls a parent function that calls another virtual function, what is called?

I learn about polymorphism, and I am confused by this situation: Let's say I have the following C ++ classes:

class A{ ... virtual void Foo(){ Boo(); } virtual void Boo(){...} } class B : public A{ ... void Foo(){ A::Foo(); } void Boo(){...} } 

I create an instance of B and call its function Foo (). When this function calls A :: Foo (), will the Boo () method of class A or B be used? Thanks!

+4
source share
3 answers

If you do not qualify a function call with a class, all method calls will be treated equal, that is, dynamic sending, if virtual, static sending, if not virtual. When you fully qualify with the class name, the method you call effectively disables the dynamic dispatch mechanism and presents a direct method call.

 class A{ virtual void Foo(){ Boo(); // will call the final overrider A::Boo(); // will call A::Boo, regardless of the dynamic type } virtual void Boo(); }; class B : public A{ void Foo(){ //Foo(); // Would call the final overrider // (in this case B: infinite recursion) A::Foo(); // Will call A::Foo, even if the object is B } void Boo(); }; 

The implicit this pointer is not an important part of the discussion here, since it happens the same way when a call is made with an explicit object:

 B b; b.Foo(); // will call B::Foo -- note 1 bA::Foo(); // will call A::Foo 

Note 1: in this example, the compiler can exit the dynamic distribution mechanism because it knows the specific type of the instance (it sees the definition and is not a link / pointer), but you can imagine that the same thing would happen if b was a link or that the same thing if it were a pointer with -> instead .

+9
source

Since Boo() is virtual, an override of the derived class is called.

Boo(); is just a short hand for this->Boo(); where you can see that the virtual function is being called through a pointer. ( this is of type A* const inside Foo() .) And virtual functions invoked by reference or pointer will always cause an override in the derived class itself (unless called from a constructor or destructor).

+2
source

Inside A,

 virtual void Foo(){ Boo(); } 

translates to this->Boo() , since Boo is declared virtual in A, the method of the derived class Boo is called. Do not try to declare Boo virtual in experiment-only - you will see that A-> Boo () receives the call.

Arpan

+1
source

Source: https://habr.com/ru/post/1314203/


All Articles