Page 221 - DCAP404 _Object Oriented Programming
P. 221
Object-oriented Programming
Notes void display (); //virtual
int sum ( );
};
void main ( )
{
baseA *ptr;
derivedD objd;
ptr = &objd;
Other Program statements
ptr->display (); //run time binding
ptr->sum ( ); //compile time binding
}
Note that the keyword virtual is be followed by the return type of a member function if a run
time is to be bound. Otherwise, the compile time binding will be effected as usual. In the above
program segment, only the display ( ) function has been declared as virtual in the base class,
whereas the sum () is non-virtual. Even though the message is given from the pointer of the base
class to the objects of the derived class, it will not access the sum ( ) function of the derived class
as it has been declared as non-virtual. The sum ( ) function compiles only the static binding.
The following program demonstrates the run time binding of the member functions of a class.
The same message is given to access the derived class member functions from the array of
pointers. As function are declared as virtual, the C++ compiler invokes the dynamic binding.
#include <iostream.h>
#include <conio.h>
class baseA {
public:
virtual void display () {
cout<< “One \n”;
}
};
class derivedB : public baseA
{
public:
virtual void display 0 {
cout<< “Two\n”; }
};
class derivedC: public derivedB
{
public:
virtual void display ( ) {
214 LOVELY PROFESSIONAL UNIVERSITY