polymorphism

Jun 19, 2014 at 3:12pm
" The compiler checks the type of reference in the object and not the type of object".How is this statement correct in context of polymorphism?
Jun 19, 2014 at 5:18pm
It isn't correct or even meaningful as written, but thanks for the tip about polymorphism, I think I can try to guess the intended meaning:

Given a reference b whose type is B&, when compiling a virtual function call b.f(), the compiler examines the type B for a matching function declaration, not the dynamic type of the object to which b refers.

For example:
1
2
3
4
5
6
7
8
9
10
struct B { virtual B* f() { return nullptr;} };
struct D : B { D* f() override { return nullptr;} };
int main()
{
    D obj;
    B& b = obj;

    b.f(); // the return type of this call is B*
           // even though D::f() is called
}

Topic archived. No new replies allowed.