Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right behavior when auto meets polymorphism and virtual function?

Tags:

c++

c++11

auto

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?

like image 929
BlackMamba Avatar asked Jul 12 '16 05:07

BlackMamba


People also ask

How can polymorphism be achieved through virtual functions?

Virtual Functions and Runtime Polymorphism in C++ Runtime polymorphism can be achieved only through a pointer (or reference) of base class type. Also, a base class pointer can point to the objects of base class as well as to the objects of derived class.

Does virtual function come under polymorphism?

A virtual function is a special type of function that, when called, resolves to the most-derived version of the function that exists between the base and derived class. This capability is known as polymorphism.

What is polymorphism and virtual function?

A virtual function is a member function which is declared in the base class using the keyword virtual and is re-defined (Overriden) by the derived class. The term Polymorphism means the ability to take many forms. It occurs if there is a hierarchy of classes which are all related to each other by inheritance.

Why do we need runtime polymorphism in C++?

Polymorphism is useful any time that the software can't be told at compile time exactly what everything is going to be at runtime, or when you need a container to be able to hold a heterogeneous assortment of things that all implement a common interface.


1 Answers

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();
like image 181
songyuanyao Avatar answered Oct 15 '22 12:10

songyuanyao