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?
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With