Explain the type of polymorphism with code
//C++ program to demonstrate compile time polymorphism using operator overloading
#include <iostream>
using namespace std;
class A
{
private:
int count;
public:
A() : count(10) {}
void operator --()
{
count = count - 3;
}
void display()
{
cout << "Count: " << count;
}
};
int main()
{
A a;
--a; //Decrement operator has been overloaded to work on object
a.display();
return 0;
}
//C++ program to demonstrate runtime polymorphism
#include <iostream>
using namespace std;
class Parent
{
public:
virtual void print() //Parent virtual function
{
cout << "Print parent class" << endl;
}
void show()
{
cout << "Show parent class" << endl;
}
};
class Child : public Parent {
public:
void print()
{
cout << "Print child class"<< endl;
}
void show()
{
cout << "Show parent class"<< endl;
}
};
int main()
{
Parent* pptr;
Child c;
pptr = &c;
// Virtual function bound at run time
pptr->print();
// Non virtual function bound at compile time
pptr->show();
}
Comments
Leave a comment