There is a class Base which has a function add that inputs integers from the users and prints their sum. There's another class called Derived which publicly inherits the Base class and it also has a function add but it takes real numbers as inputs (basically float) and prints their sum.
Now what I want is for the user to input 2 numbers and the code to automatically know which function to call based on the type of input using runtime polymorphism.
For eg. if I give the inputs 2 and 3, it should print 5 and then "in base class" and if I give inputs as 3.5 and 2.5, it should print 6.0 and "in derived class".
The problem I'm facing with my code is that even if I'm giving the inputs as 2 and 3, it is calling the function of the derived class, as it is implicitly converting the integer inputs to float.
Here's my code:
#include <iostream>
using namespace std;
class Base {
public:
virtual void add() {
int a, b, c;
cin >> a >> b;
c = a + b;
cout << c << endl;
cout << "base" << endl;
}
};
class Derived : public Base {
public:
void add() {
float a, b, c;
cin >> a >> b;
c = a + b;
cout << c << endl;
cout << "derived" << endl;
}
};
int main() {
Base* ptr;
Derived d;
ptr = &d;
ptr->add();
return 0;
}
I tried doing it normally and also tried using virtual but it's not helping.
Edit:
Here's the entire question: Perform addition of two number using the concept of runtime polymorphism. Here, you have to create a Base class and Derived class. The Derived class should be derived from Base class and the both class will contain an add() function. In the Base class add() function is used to add two integers and in Derived class the add() function is used to add two real numbers. Finally, the real numbers addition will be displayed as the output.
Looks like it's just a dumb question
Now what I want is for the user to input 2 numbers and the code to automatically know which function to call based on the type of input using runtime polymorphism.
This is not how polymorphism works. Virtual dispatch in a nutshell:
ptr->add();
ptr
is a pointer to Base
. Base::add
is virtual, hence the dynamic type of the object determines which method is called. The object is of type Derived
, hence Derived::add
is called.
This is how it is decided what method is called. Once called, it does not automatically get replaced by a different method depending on some user input.
Moreover, if you use std::cin
to read integers, then the result will always be stored in that integers:
int a, b, c;
cin >> a >> b;
Entering 2.0
and 3.0
will not automagically turn a
and b
into float
s. Similarly
float a,b,c;
cin >> a >> b;
If you enter 1
and 2
then the values stored in a
and b
are floating point numbers. The types of variables does not automatically change depending on user input.