Hi, I was wondering what is Polymorphism? I have been reading ebooks and websites but I just don't understand when to implement it or how for that matter.
Do I use virtual functions or function polymorphism ?
I know that in order to use polymorphism, you might have to inherit from other class.
I created a super class, and derived classes. Because the derived classes have common attributes with each other..
So what I did was create a virtual function to enforce restrictions in the positions of the each child object instances. For example class 1 object might check to see if age is between 1-4 and the other class to see if age is between 4-10.
Which brings me to the question of virtual functions. What is the point of it? I will just give an example class
Code:
class Animal:
{
private:
int numFeet ;
int Age ;
int height ,weight ;
public:
Animal()
{
numFeet = 0 ;
Age = 0 ;
height = 0 ;//and so on
}
virtual void setAge(int) =0;
}
class Dog:public Animal
{
public:
Dog::setAge(int x)
{
if(x>1 && x <4 )
{
Age = x ;
}
else
{
Age = 0 ;
}
}
}
}
class Human:public Animal
{
public:
Human::setAge(int x)
{
if(x>4 && x <10 )
{
Age = x ;
}
else
{
Age = 0 ;
}
}
}
from that because the way setAge() inherited from Animal is defined I could instead
create each implementation of setAge() in the different classes without bothering with a virtual function, it looks like the same thing to me.
if that is true the only thing I can see with a virtual function is that it is a way of making a superclass or abstract class from being instantiated.
while I at least have some understanding of inheritance I don't get polymorphism
i have a super class and derived classes inherit from them. while they perform the same operation, i want them to be able to change the operation they perform- where I am sure polymorphism comes in, changing their behavior.
Code:
class Thing:
{
private :
int h,w;
bool isTrue ;
public:
draw(int x1,int x2) ;
draw(int x1,int y1,x2,y2) ;
draw(int x1,int y1,x2,y2,x3,y3) ;
}
class Child1:public Thing
{
}
class Child2:public Thing
{
}
from the above code, each derived class should be able to change how they draw itself, a triangle will use the 3rd draw, a rectangle the first draw() and so on.
So i used function polymorphism. Which is the easiest way I could implement it.
But how do I use one function draw() to able to draw all the shapes just using the draw() ?
Please, i need to understand poly.