Answer to Question #188436 in C++ for Waleed Abid

Question #188436

Write

a program that declares two classes. The parent class is called Simple that has two data members’ num1 and num2 to store two numbers. It also has four member functions.


·       

The add() function adds two numbers and displays the result.


·       

The sub() function subtracts two numbers and displays the result.


·       

The mul() function multiplies two numbers and displays the result.    

The div() function divides two numbers

and displays the result.


The child class is called Complex that overrides all four functions. Each function

in the child class checks the value of data members. It calls the corresponding

member function in the parent class if the values are greater than 0. Otherwise it displays error message.


1
Expert's answer
2021-05-03T07:54:02-0400
#include <iostream>
class Simple
{
public:
	Simple() {};
	Simple(float n, float m) {
		num1 = n;
		num2 = m;
	}
	void set_num1(float n) {
		num1 = n;
	}
	float get_num1() {
		return num1;
	}
	void set_num2(float n) {
		num2 = n;
	}
	float get_num2() {
		return num2;
	}
	virtual void add() {
		std::cout << num1 + num2 << std::endl;
	}
	virtual void sub() {
		std::cout << num1 - num2 << std::endl;
	}
	virtual void div() {
		std::cout << num1 / num2 << std::endl;
	}
	virtual void mul() {
		std::cout << num1 * num2 << std::endl;
	}


protected:
	float num1{ 0 };
	float num2{ 0 };
};


class Complex: public Simple
{
public:
	Complex();
	Complex(float n, float m) {
		num1 = n;
		num2 = m;
	}
	 void add() override{
		 if (num1 > 0 && num2 > 0) {
			 Simple::add();
		 }
		 else {
			 std::cout << "Invalid argument values" << std::endl;
		 }
	}
	 void sub() override {
		 if (num1 > 0 && num2 > 0) {
			 Simple::sub();
		 }
		 else {
			 std::cout << "Invalid argument values" << std::endl;
		 }
	 }
	 void mul() override {
		 if (num1 > 0 && num2 > 0) {
			 Simple::mul();
		 }
		 else {
			 std::cout << "Invalid argument values" << std::endl;
		 }
	 }
	 void div() override {
		 if (num1 > 0 && num2 > 0) {
			 Simple::div();
		 }
		 else {
			 std::cout << "Invalid argument values" << std::endl;
		 }
	 }

private:
};

int main()
{
	// example work program
	Simple test_1(3, 5);
	Simple test_2(-6, 5);
	Complex test_3(3, 5);
	Complex test_4(-6, 5);
	test_1.add();
	test_2.mul();
	test_3.add();
	test_4.mul();
	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