Loading....
Coupon Accepted Successfully!

 

Array Of Pointers

Polymorphism refers to late or dynamic binding; that is, the selection of an entity is decided at run time. In class hierarchy, methods with similar names can be defined, which perform different tasks, and then, the selection of the appropriate method is done using dynamic binding. Dynamic binding is associated with object pointers. Thus, addresses of different objects can be stored in an array to invoke functions dynamically. The following program explains this concept:
 

15.7 Write a program to create array of pointers. Invoke functions using array objects.

#include<iostream.h>

#include<constream.h>

class A

{

public:

virtual void show()

{

cout<<“A\n”;

}

};

class B : public A

{

public:

void show() {cout<<“B\n”;}

};

class C : public A

{

public:

void show()

{cout<<“C\n”;

}

};

class D : public A

{

public:

void show()

{

cout<<“D\n”;

}

};

class E : public A

{

public:

void show()

{

cout<<“E”;

}

};

void main()

{

clrscr();

A a;
B b;
C c;
D d;
E e;
A *pa[]={&a,&b,&c,&d,&e};

for ( int j=0;j<5;j++)
pa[j]->show();

}

OUTPUT
A
B
C
D
E


Explanation:
In the above program, class A is a base class. The classes B, C, D, and E are classes derived from class A. All these classes have a similar function show(). In function main(), a, b, c, d, and e are objects of classes A, B, C, D, and E, respectively. The function show() of the base class is declared virtual. An array of pointer *pa is declared, and it is initialized with addresses of the base and derived class objects; that is, a, b, c, d, and e. Using for loop and array, each object invokes function show(). The output is as shown above. If the base class function show() is non-virtual, then the very time function show() of base class is executed. Figure illustrates this concept more clearly.
 

Fig: Early and late binding of functions




Test Your Skills Now!
Take a Quiz now
Reviewer Name