Professional Documents
Culture Documents
Pointers, Virtual Functions & Polymorphism III
Pointers, Virtual Functions & Polymorphism III
}
Virtual Functions
When we use the same function name in both the base and
derived classes, the function in base class is declared as
virtual using the keyword virtual preceding its normal
declaration.
When a function is made virtual, C++ determine which
function to use at run time based on the type of object
pointed to by the base pointer, rather than the type of the
pointer.
Thus, by making the base pointer to point to different
objects, we can execute different versions of the virtual
function.
Virtual Functions
#include<iostream.h> class derived : public base
class base {
{ public:
public: void display( )
void display( ) {
{ cout<<“\nDisplay Derived”;
cout<<“\nDisplay Base ”; }
} virtual void show( )
virtual void show( ) {
{ cout<<“\nShow Derived”;
cout<<“\nShow Base”; }
} };
};
Virtual Functions
void main( )
OUTPUT
{
base b;
derived d; bptr points to base
base *bptr;
cout<<“\nbptr points to base\n”; Display Base
bptr = &b; Show Base
bptr -> display( );
bptr -> show( ); bptr points to derived
cout<<“\nbptr points to derived\n”; Display Base
bptr = &d; Show Derived
bptr -> display( );
bptr -> show( );
}
About bptr