Activity # 1:: Objectives of The Lab
Activity # 1:: Objectives of The Lab
Syntax:
class class_name
{
friend data_type function_name(argument/s); // syntax of friend
function.
};
Activity # 1:
#include<iostream>
using namespace std;
class Distance {
private:
int meter;
public:
friend int func(Distance); //friend function
};
int func(Distance d){
//function definition
d.meter=10; //accessing private data from non-member function
return d.meter;
}
int main(){
Distance D;
cout<<"Distace: "<<func(D);
return 0;
}
Arifa Awan
Lab 04 : Understanding friends and overloading in C++
Arifa Awan
Lab 04 : Understanding friends and overloading in C++
Operator overloading:
The concept of overloading is generally used when a program block conceptually
executes the same task but with a slight distinctness in a set of parameters. The
concept of overloading is generally used when a program block conceptually
executes the same task but with a slight distinctness in a set of parameters.
There are some C++ operators which we can't overload.
Class member access operator (. (dot), .* (dot-asterisk))
Scope resolution operator (::)
Conditional Operator (?:)
Size Operator (sizeof)
Operator overloading is one of the most exciting features of object oriented
programming. It can transform complex, obscure program listings into intuitively
obvious ones. For example, statements like
d3.add_distances(d1, d2);
or the similar
d3 = d1.add_distances(d2);
can be changed to the much more readable
d3 = d1 + d2;
The term operator overloading refers to giving the normal C++ operators,
such as +, *, <=, and +=, additional meanings when they are applied to
user-defined data types like classes.
Defining Operator Overloading
To define an additional task to an operator, we must specify its means in
relation to the class to which the operator is applied. This is done by
using the operator function. The general form of an operator function is:
return_type classname :: operator op(arglist)
{
Function body // task defined
}
It can be class member and can be a friend function.
Return-type operator op (arg list)
{
// for inside the class
}
where :
Arifa Awan
Lab 04 : Understanding friends and overloading in C++
Arifa Awan