Inheritance- Code with Harry-Lecture 41 solution (Multiple inheritance)
Create 2 classes:
1. SimpleCalculator - Takes input of 2 numbers using a utility function and perfoms +, -, *, / and displays the results using another function.
2. ScientificCalculator - Takes input of 2 numbers using a utility function and perfoms any four scientific operation of your chioice and displays the results using another function.
Create another class HybridCalculator and inherit it using these 2 classes:
Q1. What type of Inheritance are you using?
Q2. Which mode of Inheritance are you using?
Q3. Create an object of HybridCalculator and display results of simple and scientific calculator.
Q4. How is code reusability implemented?
Ans1. Multiple level inheritance
Ans2. Public mode Ans3. #include <iostream> #include <cmath> using namespace std; class SimpleCalculator { protected: float result; int number_1,number_2; char operand; public: void get_number(int n1,int n2) { number_1=n1; number_2=n2; } void calculation() { cout<<"What operation do you want to perform ?"<<endl; cout<<"1.For multiplication, enter *"<<endl; cout<<"2.For divison, enter /"<<endl; cout<<"3.For addition, enter +"<<endl; cout<<"4.For subtraction, enter -"<<endl; cin>>operand; if(operand=='*') result=number_1*number_2; if(operand=='/') result=float (number_1/number_2); if(operand=='+') result=number_1+number_2; if(operand=='-') result=number_1-number_2; } void display() { cout<<result<<endl; } }; class ScientificCalculator{ protected: float res; int num_1; char op; public: void get_num(int n1) { num_1=n1; } void calc() { cout<<"What operation do you want to perform ?"<<endl; cout<<"1.For tan of angle, enter t"<<endl; cout<<"2.For sine of angle, enter s"<<endl; cout<<"3.For cosine of angle, enter c"<<endl; cout<<"4.For logarithim of a number, enter l"<<endl; cin>>op; if(op=='t') res=tan(num_1); if(op=='s') res=sin(num_1); if(op=='c') res=cos(num_1); if(op=='l') res=log(num_1); } void dis() { cout<<res<<endl; } }; class HybridCalculator:public SimpleCalculator,public ScientificCalculator{ public: HybridCalculator(){} HybridCalculator(int n1,int n2) { get_number(n1,n2); calculation(); display(); } HybridCalculator(int n1) { get_num(n1); calc(); dis(); } }; int main() { cout<<" Do you want to enter one number or two number?"<<endl; cout<<"Type 1 or one number and 2 for two numbers"<<endl; int option; cin>>option; int nu1,nu2; if(option==1) { cout<<"Enter your number"<<endl; cin>>nu1; } if(option==2) { cout<<"Enter your numbers"<<endl; cin>>nu1>>nu2; } HybridCalculator h1(); HybridCalculator h2(nu1,nu2); HybridCalculator h3(nu1); return 0; } Ans 4. I am not repeating any function or operation that I wrote in base class. Also, the objects of class that were made in main class are responsible for the execution of methods (that are present in base classes). Hence, code reusability is implemented
Comments
Post a Comment