What is the correct behavior when an auto responds to polymorphism and a virtual function?

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; bf(); } 

for d->f(); Exit D it is right. But for bf(); the output is B Is it correct?

+7
c ++ c ++ 11 auto
source share
1 answer

Is it correct?

That's right, the type is inferred at compile time. auto uses the same rules for outputting a template argument to output a type based on a static type; dynamic polymorphism is not considered.

For this case, type d is equal to B* , then type *d is equal to B , therefore type B is equal to B Then *d will be adjusted with segments to B , for bf() B::f() should be called.

The code is equivalent to the following, which may be clearer.

 B b = *d; bf(); 
+14
source share

All Articles