cplusplus
C++ Lists

Virtual function and Polymorphism: C++

A member of a class that can be redefined in its derived classes is known as a virtual member. In order to declare a member of a class as virtual, we must precede its declaration with the keyword virtual. When a function is made virtual, C++ determines which function to be used at runtime based on the type of the 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. A class that declares or inherits a virtual function is called a polymorphic class. One important point to remember is that we must access virtual functions through the use of a pointer declared as a pointer to the base class.

 Example 
#include <iostream>
#include <cstring>

using namespace std;

class media
{
protected:
char title[50];
float price;
public:
media(char *s, float a)
{
strcpy(title, s);
price = a;
}
void display(){ cout<< “default”;} //empty virtual function
};

class book: public media
{
int pages;

public:
book(char *s, float a, int p) : media(s,a)
{
pages =p;
}
void display();
};

class tape: public media
{
float time;

public:
tape(char *s, float a, float t):media(s,a)
{
time =t;
}
void display();
};

void book ::display()
{
cout<<“\n Title: “<<title;
cout<<“\n Pages: “<<pages;
cout<<“\n Price: “<<price<<endl;
}
void tape::display()
{
cout<<“\n Title: “<<title;
cout<<“\n Play tinme : “<<time<<“mins”;
cout<<“\n Price: “<<price<<endl;
}

int main()
{
char * title = new char[30];
float price, time;
int pages;

// Book details
cout<<“\n ENTER BOOK DETAILS”;
cout<<” Title: “; cin>>title;
cout<<” Price: “; cin>>price;
cout<<” Pages: “; cin>>pages;

book book1(title,price,pages);

// Tape details
cout<<“\n ENTER TAPE DETAILS”;
cout<<” Title: “; cin>>title;
cout<<” Price: “; cin>>price;
cout<<” Play time (mins): “; cin>>time;

tape tape1(title, price, time);

media* list[2];

list[0] = &book1;
list[1] = &tape1;

cout<<“\n MEDIA DETAILS”;

cout<<“\n ……BOOKS……”; list[0] ->display(); // display book details

cout<<“\n…….TAPE……”; list[1] ->display(); //display tape details

return 0;
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.