Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

EXPERIMENT 06

Operator Overloading
Objectives:
 To implement the concepts of Operator Overloading.
Equipment /Tool:
PC, Microsoft Visual Studio 2013
Background:

Operator Overloading:
Example: Overloading Unary Operators

2
Fig 6.1: Operator Arguments

3
Nameless Temporary Object:

4
Postfix Notation:

5
Procedure:

Perform all the tasks and provide your code and result in the space below the questions.
Lab Tasks

Q1) Write a program that overload “!” operator to take NOT of an integer member from class
invert

Answer:

Solution

CODE:
#include <iostream>
#include <conio.h>
using namespace std;
class invert

{
private:
int abd;
public:
invert() : abd(0)
{}
int oper()
{
return abd;
}
void operator !()
{
abd = !abd;
}
};
void main()
{

invert abd;
!abd;
cout << abd.oper()<<endl;
system("pause");
}

Output:
6
Q2) Write a program to add and subtract two complex numbers using operator overloading.

Answer:
Solution

CODE:
#include<iostream>
#include<conio.h>
using namespace std;
class complex

{
int real;
int imag;
public:
complex() :real(0), imag(0)
{}
complex(int a, int b)

{
real =a;

imag = b;

}
complex operator +(complex c)
{

complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return(temp);
}
complex operator -(complex c)
{
complex temp;
temp.real = real - c.real;
temp.imag = imag - c.imag;
return(temp);
}
void show()
{
cout << "by performing addtion:" << endl;
cout << real << endl;

7
cout << imag << endl;
}
};
void main()

{
complex c1(9, 8), c2(17, 9), c3, c4;
c3 = c1 + c2;
c3.show();
c4 = c1 - c2;
c4.show();
_getch();
}

Output:

Q3) Write a C++ program to multiply two matrices. For that, create a class ‘matrix’ that contains
a matrix ‘arr’. Overload the operator ‘*’ for ‘matrix’ class which will perform matrix
multiplication.

Answer:

Solution

You might also like