why will derived class function get called?

Hi guys when studying about references I came across some code that just confuses the day lights out of me,

why would D's foo() be called instead of B's foo?

this just doesn't seem logical to me

thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  struct B
{
    virtual void foo() const;
};

struct D : B
{
    virtual void foo() const;
};

//B bar();
D bar();

const B& b = bar();

b.foo(); // This will call D::foo()

// In the end the temporary bound by b will be correctly destroyed
// using the destructor of D. 
Why not? The object is a D.
Topic archived. No new replies allowed.