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.
#include<iostream>
using namespace std;
class Simple{
protected:
float num1;
float num2;
public:
Simple() {};
Simple(float num1, float num2) {
this->num1 = num1;
this->num2 = num2;
}
virtual void add() {
cout <<"Sum = "<< (num1 + num2) << "\n";
}
virtual void sub() {
cout <<"Difference = "<< (num1 - num2) << "\n";
}
virtual void div() {
cout <<"Quotient = "<< (num1 / num2) <<"\n";
}
virtual void mul() {
cout <<"Product = "<<(num1 * num2) << "\n";
}
};
class Complex: public Simple
{
public:
Complex();
Complex(float num1, float num2) {
this->num1 = num1;
this->num2 = num2;
}
void add() override{
if (num1 > 0 && num2 > 0) {
Simple::add();
}
else {
cout << "Invalid argument values"<< "\n";
}
}
void sub() override {
if (num1 > 0 && num2 > 0) {
Simple::sub();
}
else {
cout << "Invalid argument values" << "\n";
}
}
void mul() override {
if (num1 > 0 && num2 > 0) {
Simple::mul();
}
else {
cout << "Invalid argument values"<< "\n";
}
}
void div() override {
if (num1 > 0 && num2 > 0) {
Simple::div();
}
else {
cout << "Invalid argument values"<< "\n";
}
}
};
int main(){
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();
system("pause");
return 0;
}
Comments
Leave a comment