Polymorphism in C++
Submitted by moazkhan on Wednesday, August 6, 2014 - 12:57.
Polymorphism in C++
In this part you will learn: 1. Polymorphism 2. C syntax 3. Showing output In this tutorial I will teach you about the concept of Polymorphism in C++. What is a Polymorphism? Polymorphism enables to write programs that process objects of classes (that are part of the same hierarchy) as if they are all objects of the hierarchy’s base class. In polymorphism we can access functions of the derived class object through base class pointer. Person Class Before we can start writing the program we need to have a little knowledge about virtual functions. To achieve this functionality we need to declare some functions virtual. We need to override the functions in the derived class and declare those functions virtual in the base class. This is because when we call a function using base class pointer which is pointing to derive class object the compiler sees the type of pointer that is being used to call the function and executes the function of the base class. Whereas if we make the function in the base class virtual then in that case the compiler sees the type of object the pointer is pointing at and then executes that function of the derived class. Basic Step: Open Dev C++ then File > new > source file and start writing the code below.- #include<stdio.h>
- #include<conio.h>
- #include<iostream>
- using namespace std;
- class Person
- {
- protected:
- char name[40];
- public:
- void getname()
- {
- cout<<"Enter name:";
- cin>>name;
- }
- void putname()
- {
- cout<<endl<<"Name is:"<<name;
- }
- virtual void getdata(){};
- virtual bool isOutstanding(){};
- };
- class Professor: public Person
- {
- private:
- int numpubs;
- public:
- void getdata()
- {
- Person::getname();
- cout<<"Enter publications:";
- cin>>numpubs;
- }
- bool isOutstanding()
- {
- return (numpubs>100)?true:false;
- }
- };
- class Student: public Person
- {
- private:
- float gpa;
- public:
- void getdata()
- {
- Person::getname();
- cout<<"Enter GPA:";
- cin>>gpa;
- }
- bool isOutstanding()
- {
- return(gpa>3.5)?true:false;
- }
- };
- int main()
- {
- Person* persPtr[2];
- Professor p;
- persPtr[0]=&p;
- persPtr[0]->getdata();
- Student s;
- persPtr[1]=&s;
- persPtr[1]->getdata();
- for(int i=0;i<2;i++)
- {
- persPtr[i]->putname();
- if(persPtr[i]->isOutstanding())
- {
- cout<<endl<<"This Person is outstanding"<<endl;
- }
- }
Add new comment
- 761 views