Write a C++ program for function overloading in adding the distance between objects.
AIM:
Write a C++ program for function overloading in adding the distance between
objects.
THEORY:
In some programming
languages, function
overloading or method overloading is the ability to
create multiple methods of the same name with different implementations.
Calls to an overloaded function will run a specific implementation of that
function appropriate to the context of the call, allowing one function call to
perform different tasks depending on context.
For example, doTask() and doTask(object
O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas
the former does not require a parameter, and is called with an empty parameter
field. A common error would be to assign a default value to the object in the
second method, which would result in an ambiguous call error,
as the compiler wouldn't know which of the two methods to use.
Another
appropriate example would be a Print(object O) method. In this
case one might like the method to be different when printing, for example, text
or pictures. The two different methods may be overloaded as Print(text_object
T); Print(image_object P). If we write the overloaded print methods for all
objects our program will "print", we never have to worry about the
type of the object, and the correct function call again, the call is always: Print(something).
SOURCE
CODE:
#include<iostream>
using namespace std;
class dist {
public:
int
feet,inch;
dist() {}
dist(int
x,int y) {
feet=x;
inch=y;
}
dist(float
m,float n) {
feet=m;
inch=n;
}
void
display() {
cout<<"\n
the distance is \n";
cout<<"feet"<<feet<<inch<<"inch";
}
void
sum(dist ob1,dist ob2) {
cout<<"\n
adding feet and inche sto two distance objects";
feet=ob1.feet+ob2.feet;
inch=ob1.inch+ob2.inch;
if(inch>=12) {
feet=feet+1;
inch=inch-12;
}
}
void
sum(int x,int y) {
cout<<"\n
adding feet and inches to single object";
feet+=x;
inch+=y;
if(inch>=12){
feet=feet+1;
inch=inch-12;
}
}
};
int main(){
dist
ob1(8,9),ob2(4.0f,7.3f),ob3,ob4(3,8);
ob3.sum(ob1,ob2);
ob3.display();
ob4.sum(7,9);
ob4.display();
ob1.display();
ob2.display();
}
Labels: oop through c++ lab
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home