0% found this document useful (0 votes)
11 views

Untitled Document

Uploaded by

mn8662246
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Untitled Document

Uploaded by

mn8662246
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

Overloading Unary Minus using a Member Function

When overloading using a member function, the operator function is a member of the
class and works on the calling object.

#include<iostream>

class Distance {

private:

int feet;

int inches; Practicalkida.com


public:

// Constructors

Distance() : feet(0), inches(0) {}

Distance(int f, int i) : feet(f), inches(i) {}

// Member function to overload unary minus (-)

Distance operator- () const {

return Distance(-feet, -inches);

// Function to display Distance

void displayDistance() const {

std::cout << "F: " << feet << " I: " << inches << std::endl;

};
int main() {

Distance D1(11, 10), D2(-5, 11);

Distance D3 = -D1; // Using member function

D3.displayDistance();

Distance D4 = -D2; // Using member function

D4.displayDistance();
Practicalkida.com
return 0;

2. Overloading Unary Minus using a Friend Function

When overloading using a friend function, the operator function is defined outside the
class but is granted access to the class's private and protected members.

#include<iostream>

class Distance {

private:

int feet;

int inches;

public:

// Constructors

Distance() : feet(0), inches(0) {}


Distance(int f, int i) : feet(f), inches(i) {}

// Friend function to overload unary minus (-)

friend Distance operator- (const Distance& d);

// Function to display Distance

void displayDistance() const {

std::cout << "F: " << feet << " I: " << inches << std::endl;

}
Practicalkida.com
};

Distance operator- (const Distance& d) {

return Distance(-d.feet, -d.inches);

int main() {

Distance D1(11, 10), D2(-5, 11);

Distance D3 = -D1; // Using friend function

D3.displayDistance();

Distance D4 = -D2; // Using friend function

D4.displayDistance();

return 0;

}
Member Function: The overloaded - operator as a member function is called on the
object directly (e.g., -D1). The function works on this pointer, representing the
calling object.

Friend Function: The overloaded - operator as a friend function takes an object of the
class as a parameter and returns a new object with negated values.

Practicalkida.com

You might also like