Following code results in compilation error.
error: no matching function for call to ‘D::print(int)’
Error is at following line
d_ptr->print(5);
#include<iostream>
using std::cout;
class B {
public:
virtual void print() {
cout << "B::print()\n";
}
virtual void print(int i) {
cout << "B::print(int)\n";
}
};
class D: public B {
public:
void print() {
cout << "D::print()\n";
}
};
int main() {
D d, *d_ptr = &d;
B *b_ptr = &d;
b_ptr->print(5);
d_ptr->print(5);
return 0;
}
If I comment out the line generating an error then code is working as expected.
So my questions is why b_ptr->print(5);
is working without compilation error but d_ptr->print(5);
leads to compilation error?
If B::print(int)
was non-virtual function then it makes sense. Because in that case B::print(int)
will hide behind D::print()
.
But for virtual function, dispach happens at runtime based on virtual-function-table created for the class of the object. Then why it behaves differently when we call print()
with d_ptr
instead of b_ptr
.
I would appreciate if someone can point me to the right resource which can clear my confusion.