7
class B {
    public:
    virtual void f(){
        printf("B\n");
    }
};
class D : public B { 
    public:
    void f() {
        printf("D\n");
    }
};

int main(void)  
{  
    B* d = new D();
    d->f();
    auto b = *d; 
    b.f();
}

for d->f();, the output is D. this is right. But for b.f();, the output is B. Is this right?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
BlackMamba
  • 10,054
  • 7
  • 44
  • 67

1 Answers1

14

Is this right?

It's right, the type is deduced at compile time. auto uses the same rules of template argument deduction for type deduction, based on the static type, dynamic polymorphism won't be considered.

For this case, the type of d is B*, then type of *d is B, so the type of b is just B. Then *d will be slicing copied to b, for b.f() B::f() should be invoked.

The code is equivalent to the following which might be clearer.

B b = *d;
b.f();
Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • However, please note that if it were `auto & b = *d;` (or `auto && b = *d;` ) , then `b.f()` would have invoked the overridden f() in the derived class. – Nawaz Jul 12 '16 at 06:36