I am trying to understand "polymorphing" and so far, the code below is what i have managed so far.
Please correct me if i'm wrong about this, but i'll try to explain virtual functions. A virtual function is a function that can be redefined and also can maintain its parameters when it is redefined in a derived class
#include <iostream>
class Base {
public:
virtual ~Base() {} // a good idea for polymorphic classes
void setMembers(int a, int b) {
num1 = a;
num2 = b;
}
virtualvoid showMembers() const {
return 0;
}
protected:
int num1 = 0;
int num2 = 0;
};
class Derived : public Base {
public:
void showMembers() const override { // you don't need the 'override', but I like it.
return num1 * num2;
}
};
int main() {
Base* object1 = new Base;
Base* object2 = new Derived;
int num1;
int num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
object1->setMembers(num1, num2);
object2->setMembers(num1, num2);
std::cout << object1->showMembers() << std::endl;
std::cout << object2->showMembers() << std::endl;
// EDIT: Make sure you delete your objects properly... (or use smart pointers)
delete object1;
delete object2;
return 0;
}
EDIT:
In essence, for an object to be polymorphic you need to have a pointer/reference to an object, and that is generally reflected through the base class (as shown above).
Ah thank you very much for your response, i finally understand how to "polymorph". But i still have a few questions.
Why should I use the polymorph/virtual functions method? and for what?
What use does it have in high level programming?
EDIT
by the way, are there other ways to "polymorph"? or is using a pointer to a base class(and assigning it the address of a derived class object) to call the functions for both derived and base classes the only way to polymorph?
Generally, you would use polymorphism as one way of having one set of code doing different things, but you don't need to know exactly what is going on. A typical example of this:
In the above code, the saySomething function doesn't know (or care) what type of animal it is receiving; it is just repeating the code. This can often help structure code and as a way to add functionality easily without having to modify large portions of your code.
As for how to 'polymorph', generally using a pointer / reference to the base class is the only way to call virtual functions. However, similar effects can often be gotten with the use of templates, through techniques like 'compile-time polymorphism' (rather than 'runtime polymorphism' as above).