Professional Documents
Culture Documents
It is one of pillars of object oriented programming.In an object oriented language polymorphism allows a programmer to purse a course of action by sending a message to an object without concerning about how the software system is to implement the action (i.e One function works as different in different place)
cin>>name; cout<<"Enter the roll no"<<endl; cin>>rollno; } void derivedB::display() { cout<<"The name is"<<name<<endl; cout<<"The roll no is"<<rollno<<endl; } void main() { clrscr(); base *ptr; derivedB obj; ptr=&obj; ptr->getdata(); ptr->display(); getch(); }
class derivedB: public base { private: long int rollno; char name[20]; public: void getdata(); void display(); };
void base::getdata() { cout<<"base class getdata function"; } void base::display() { cout<<"base class display function"; } void derivedB::getdata() { cout<<"Enter the name"<<endl;
void derivedB::display() { cout<<"The name is"<<name<<endl; cout<<"The roll no is"<<rollno<<endl; } void main() { clrscr(); base *ptr; derivedB obj; ptr=&obj; ptr->getdata(); ptr->display(); getch(); }
void derivedB::getdata() { cout<<"Enter the name"<<endl; cin>>name; cout<<"Enter the roll no"<<endl; cin>>rollno; }
This function should be declared in the base class specifications It can be overloaded It should be a member function of a class There can be virtual destructors Constructors cannot be declared as virtual functions This function may or may not have function body It cannot be an ordinary stand alone function These functions are to be accessed by base class pointers If there is no code defined for a virtual function in derived class, then base class function is invoked
A body less virtual function is otherwise called. Simply defined as virtual functions with no body we use the pointer of base class to refer all the derived objects It is a normal practice to have a function in base class just for implementing virtual function but the actual coding will be done in derived class only and also the class cannot be used for creating objects.
void main() { base *list[2]; base1 b; base2 b1; clrscr(); list[0]=&b; list[1]=&b1; list[0]->show(); list[1]->show(); getch(); }
Abstract classes
A class that contains atleast one pure virtual function is said to be an abstract class.
abstract class only act as a base class for deriving other classes but does not create objects
#include<iostream.h> #include<conio.h> class book { private : int x; public : book() { x=0; }
virtual void getdata()=0; virtual void putdata()=0; }; void main() { clrscr(); cout<<"end"; getch(); }
Polymorphism is defined as the ability of objects of different classes related by inheritance to respond differently to the same member function or operator. A virtual function is one that does not really exist but never less appears real to some parts of the program. It provides a way to decide , when it is running what function to call.