Answer to Question #187774 in C++ for Shrijan Kumar

Question #187774

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.


1
Expert's answer
2021-05-02T03:05:11-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS