'function call inside polymorphic call. virtual function call
The following is calling Derived::fn2() from Derived::fn1(), where as fn2() is not virtual so it should call Base class's function. Could anyone explain why?
#include <iostream>
using namespace std;
class Base{
public:
virtual void fn1()
{
cout<<"Base function 1"<<endl;
this->fn2();
}
void fn2()
{
cout<<"Base function 2"<<endl;
}
};
class Derived : public Base{
public:
void fn1()
{
cout<<"Derived function 1 "<<endl;
this->fn2();
}
void fn2()
{
cout<<"Derived function 2"<<endl;
}
};
int main()
{
Base *b = new Derived();
b->fn1();
}
Solution 1:[1]
fn2()is not virtual so it should call Base class's function.
No, it shouldn't. Here you are why:
Derived d;
static_cast<Base&>(d).fn1();
// Calls Derived::fn1 through dynamic dispatching. In Derived::fn1, `this` is
// of type Derived*, so it will call Derived::fn2
// Output:
// Derived function 1
// Derived function 2
static_cast<Base&>(d).fn2();
// fn2() is not virtual, so you overloaded it. You're calling Base::fn2().
// Output:
// Base function 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | paolo |
