In the attached code why: p1->print(); binds dynamically? and why: p2->print(); binds statically ?
#include<iostream>
class Base{ public:
virtual void print()
{ std::cout<<"Base"<<std::endl;}
};
class Derived : public Base{
public:
virtual void print()
{ std::cout<<"Derived"<<std::endl; }
};
int main()
{
Base *p1 = new Base{ } ;
p1->print();
std::cout<<"------------------"<<std::endl;
Derived *p2 = new Derived{ } ;
p2->print();
return 0;
}
According to my knowledge a virtual functions binds dynamically if the pointer or reference is of type different than the object type being pointed to by the pointer or reference AND there must be a virtual function to activate dynamic binding.
The function
printis searched in the classes according to the static types of the pointersAs the static type of the pointer
p1isBase *when the functionprintis searched in the classBase.On the other hand, as the static type of the pointer
p2isDerived *then the functionprintis searched in the classDerived.You could write for example
in this case as the static type of the pointer
p3isBase *then the functionprintwill be searched in the classBase. But as the dynamic type of the pointer isDerived *then the functionprintof the derived class will be called.Consider the following demonstration program
The program output is
As you can see though in the class
Derivedthe function is private nevertheless it is called for the pointerp1because the pointer static type isBase *and within the classBasethe function is public.However if you will try to call the function using the pointer
p2having the static typeDerived *then the compiler will issue an error because the function within the classDerivedis private that is inaccessible.