MATH FORMULA C++ AND C
In many Cases, the function to be called is determined only at runtime. This is known as dynamic polymorphism or late binding. It is also known as run time polymorphism. Here the function to be called is selected at runtime only. It is implemented through pointers. It increases the overhead on the compiler. At the same time, it enhances the flexibility of the program. It is implemented with the help of virtual functions.
Virtual functions
Normally, a single pointer object can refer both the superclass as well as the subclass. pointer of the base class refer to object of derive .but this way, these pointer can only call the inherited function of derive class ex:-the pointer can only call the member of the superclass. it cannoy call the memberss of the susbclass.
Sample Program
There i superclass shape. it take two parameter. dimension 1 and dimension 2. in the area function,it calculate the area of the rectangle which is consider as the display shape. it has two subclass : triangle & cylinder. depending or user’s input, the corresponding class method should be invoked.
#include<iostream.h>
#include<conio.h>
class shape
{
protected:
int x,y;
shape(int a, int b)
{
x=a;
y=b;
}
void area()
{
cout<<“\nArea of Rectangle = “<<x*y;
}
};
class cylinder:public shape
{
public:
cyinder(int a,int b):shape(a,b)
{}
void area()
{
cout<<“\nArea of Triangle=”<<0.5 * x * y;
}
void main()
{
clrscr();
int m,n,sh,ch;
cout<<“\nEnter two number\n”;
cin>>m>>n;
shape * sp;
do
{
cout<<“\nchoose a shape\n1) Triangle\n2) Rectangle \n3) Cylinder\n\n”;
cin>>sh;
if(sh==2)
{
shape s1(m,n);
sp=&s1;
}
else if(sh==3)
{
cylinder s2(m,n);
sp=&s2;
}
else
{
triangle s3(m,n);
sp=&s3;
}
sp->area();
cout<<“\nWish to continue (0 for no)/(1 for yes)\n”;
cin>>ch;
}while(ch==1);
}
Your output is:-
enter the two number 12 45
choose a shape
1
area of rectangle is =540
wish to continue (0 for no) / (1 for yes)
1
choose a shape
- triangle
- rectangle
- cylinder
3
area of rectangle is =540
wish to continue (0 for no) / (1 for yes)
Result:
the user except to have the area of the choosen shape but in the output, whichever shape you choose , you always get the area of rectangle. so, the output was not as excepted. to get rid of the problem, apply the keyword virtual before the area function of shape (super) class i.e.
virtual void main()
{
count<<“\n area of rectangle = “<<x*y;
}
this will generate the excepted output as the compiler now select the function based on content of the pointer sp rather than the type of the pointer sp. so, sp->area calls different version of area depending on the shape chosen by the user.this is late binding or run time polymorphism
thanks for this latest formula fot math
Thats an awesome post, my name is ronald a. spinabella and I love seo and digital marketing.