#include <bits/stdc++.h>
using namespace std;
class Base
{
public:
virtual void print()
{
cout << "Base class print function \n";
}
void invoke()
{
cout << "Base class invoke function \n";
this -> print(); // case: 1
print(); // case: 2
Base::print(); // case: 3
}
};
class Derived: public Base
{
public:
void print()
{
cout << "Derived class print function \n" ;
}
void invoke()
{
cout << "Derived class invoke function \n";
this -> print();
}
};
int main()
{
Base *b = new Derived;
b -> invoke();
return 0;
}
For the above code I have hard time understanding how vptr and vtable of Derived and Base class is working for comments 1, 2 and 3. Why in case 1 and case 2 derived print is called ? A little arrow diagram will be very appreciated.
this -> print();is justprint()and uses the vtable to call the member of the actual type, as the function is virtual. That's what virtual functions are used for.Base::print();just calls the indicated function, whether it is virtual or not. Often used by derived classes to first call the base class function and then do it own thing.