write a program to implement run time polymorphism. Take a function check() in base class. Redefine the function in derived classes. One will calculate factorial of a number. Other will display multiplication table of that number.
#include <iostream>
using namespace std;
class Base
{
public:
void set_value(int n) {
m_value = n;
}
int get_value() {
return m_value;
}
virtual void check() {
cout << get_value() << endl;
}
int m_value{ 0 };
private:
};
class Factorial :public Base
{
public:
Factorial() {};
void check()
{
int result = 1;
for (int i = 1; i <= m_value; i++) {
result *= i;
}
cout << result<<endl;
}
private:
};
class Multiplication :public Base
{
public:
Multiplication() {};
void check()
{
for (int i = 1; i < 10; i++) {
cout << i << "*" << m_value << "=" << i * m_value << endl;
}
}
private:
};
int main()
{
//example
Factorial test_1;
Multiplication test_2;
test_1.set_value(8);
test_2.set_value(42);
test_1.check();
test_2.check();
return 0;
}
Comments
Leave a comment