C++ | Introduction to operator overloading

Introduction

This is a tutorial for operator overloading in c++. The program is given below that uses operator overloading to add two numbers. The program is extendable. Go enjoy the program. Lets begin……

Program for operator overloading

#include<iostream.h>
#include<conio.h>
//declare class
class sum
{
public:
int x;
void getx(void)
{
cout<<“Enter number.”<<endl;
cin>>x;
}
sum operator + (sum t)
{
sum tmp;
tmp.x= x+ t.x;
return tmp;
}
};
//void main
void main()
{
//clear the screen.
clrscr();
//declare sum
sum a,b,c;
//Call funtions
a.getx();
b.getx();
c=a+b;
cout<<“Sum = “<<c.x;
//get character
getch();
}

Output

Enter number.
4
Enter number.
5
Sum = 9

How it works

  1. You enter two numbers.
  2. Sum is calculated and printed.

Extending it

The program can be extended by using the concept in any program.

  • Remember this is a basic part of c++ which can be used in any program….

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’.
  2. Add a class with operator overloading function.
  3. Add void main.
  4. Start program by first clearing the screen.
  5. Delcare class.
  6. Call functions
  7. Print the value.

At the end

You learnt creating the C++ program for operator overloading in c++. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s