friend functions - bamu enginebamuengine.com/wp-content/uploads/2017/05/unit-2.1.pdf · numbers...

56
FRIEND FUNCTIONS A non member function cannot have an access to the private data of a class. In some situation ,two classes like to share a particular function. C++ allows the common function to be made friendly with both the classes, thereby allowing the function to have access to the private data of these classes Such a function need not be a member of any of these classes. A friend function is not a member function, but has full access right to the private member of the class

Upload: buikiet

Post on 21-Jun-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

FRIEND FUNCTIONS• A non member function cannot have an access to the private

data of a class.

• In some situation ,two classes like to share a particular

function.

• C++ allows the common function to be made friendly with

both the classes, thereby allowing the function to have

access to the private data of these classes

• Such a function need not be a member of any of these

classes.

• A friend function is not a member function, but has full

access right to the private member of the class

FRIEND FUNCTIONSThe syntax for friend function is

class ABC

{

=======

public:

=======

friend void function1(void);

}

• The function is declared with friend keyword.

• But while defining friend function. It does not use either

keyword friend or :: operator

FRIEND FUNCTIONS• A friend, function has following characteristics.

i) It is not in the scope of the class to which it has been

declared as friend.

ii) A friend function cannot be called using the object of that

class. If can be invoked like a normal function without help

of any object.

iii) It cannot access the member variables directly & has to use

an object name dot membership operator with member

name.

iv) It can be declared either in the public or the private part of a

class without affecting its meaning.

v) Usually, it has the object as arguments.

# include<iostream.h>

class sample

{

int a, b;

public:

void setvalue()

{

a = 25; b = 40;

}

friend float mean (sample s);

};

float mean(sample s)

{

return float(s.a + s.b)/ 2.0;

}

main ( )

{

sample x ;

x.setvalue();

cout << “ Mean Value = “;

mean(x);

}

output.

Mean value = 32.5

FRIEND FUNCTIONS• Member function of one class can be friend functions of

another class.

• All the member functions of one class can be friend

functions of another class, by declaring that class as a friend

class

• A friend function work as a bridge between the classes

• A friend function can be called by reference

• Following program shows how to use a common friend

function to exchange private value of two classes.

Area of rectangle using friend function

#include <iostream.h>

#include<conio.h>

class Rectangle

{

int width, height;

public:

Rectangle(int w = 10, int h = 10)

{

width=w;

height=h;

}

friend void display(Rectangle r);

};

void display(Rectangle r)

{

cout <<“area of rectangle is:”<< r.width * r.height << endl;

}

void main ()

{

Rectangle rect;

display(rect);

getch();

}

Addition of two complex numbers using friend#include<iostream.h>

#include<conio.h>

class Cmplx1

{

int real,imagin;

public :

void get()

{

cout<<"\n\n\tENTER THE REAL PART : ";

cin>>real;

cout<<"\n\n\tENTER THE IMAGINARY

PART : ";

cin>>imagin;

}

friend void sum(Cmplx1,Cmplx1);

};

void sum(Cmplx1 c1,Cmplx1 c2)

{

cout<<"\n\t\tRESULT : "<<endl;

cout<<c1.real<<" + i "<<c1.imagin<<endl;

cout<<c2.real<<" + i "<<c2.imagin<<endl;

cout<<c1.real+c2.real<<" + i

“<<c1.imagin+c2.imagin;

}

void main()

{

Cmplx1 op1,op2;

clrscr();

cout<<"\n\n\tADDITION OF TWO

COMPLEX NUMBERS USING FRIEND

FUNCTIONS\n\n";

cout<<"\n\tINPUT\n\n\t\tOPERAND 1";

op1.get();

cout<<"\n\n\t\tOPERAND 2";

op2.get();

sum(op1,op2);

getch();

}

Output

ADDITION OF TWO COMPLEX

NUMBERS USING FRIEND

FUNCTIONS

INPUT

OPERAND 1

ENTER THE REAL PART : 21

ENTER THE IMAGINARY PART : 10

OPERAND 2

ENTER THE REAL PART : 15

ENTER THE IMAGINARY PART : 5

RESULT :

21 + i 10

15 + i 5

36 + i 15

Returning objects

• A function can not only receive objects as arguments but

also can return them.

• Following program shows how objects can be returned

#include <iostream.h>

class complex

{

float x, y;

public:

void input (float real, float image)

{

x = real;

y = image;

}

friend complex sum (complex, complex);

void show(complex);

};

complex sum (complex c1, complex c2)

{

complex c3;

c3. x = c1.x + c2.x;

c3.y = c1.y + c2.y;

return(c3);

}

void complex ::show(complex c)

{

cout << c.x << " +j "<< c.y <<endl;

}

main ( )

{

complex A, B, C;

A.input (3.1, 5.65);

B.Input (2.75, 1.2);

C= sum (A, B);

cout << “A”;

A.show(A);

cout << “B”;

B.show(B);

cout << “C”;

C.show(C);

}

output of the program

A = 3.1 + j5 65

B = 2.75 + ji.2

C = 5.85 + j6. 85

Dynamic Objects

• The constructors can also be used to allocate memory while

creating objects.

• Due to this, the system allocates the right amount of

memory for each objects when the objects are not of the

same size.

• Thus resulting in the saving of memory.

• Allocation of memory to objects at the time of their

construction is known as dynamic construction of objects.

• The memory is allocated with the help of the new operator.

Example of Dynamic Constructor# include <iostream.h>

# include <conio.h>

# include <string.h>

class str

{ char *name;

int len;

public:

str()

{ len=0;

name=new char[len+1];

}

str(char *s)

{

len=strlen(s);

name=new char[len+1];

strcpy(name,s);

}

void show()

{

cout<<"NAME IS:->"<<name<<endl;

}

void join(str &a,str &b);

};

void str::join(str &a, str &b)

{

len=a.len+b.len;

delete new;

name=new char[len+1];

strcpy(name,a.name);

strcat(name,b.name);

};

main()

{

clrscr();

char *first=“firstname";

str n1(first),n2(“middlename"),

n3(“surname"),n4,n5;

n4.join(n1,n2);

n5.join(n4,n3);

n1.show();

n2.show();

n3.show();

n4.show();

n5.show();

}

Dynamic Objects

• The above program uses two constructors.

• The first is an empty constructor that allows us to declare an

array of string.

• The second constructor initialized the length of the string,

allocates necessary space for the string to be stored and

creates the string itself.

• Note that one additional character space is allocated to hold

the end-of-string character \0.

Pointers to Objects

• Pointers can point to objects as well as to simple data types

and arrays

• Distance dist;

• where an object called dist is defined to be of the Distance

class.

• Sometimes, it is difficult at the time that we write the

program, how many objects are required

• When this is the case we can use new to create objects while

the program is running

#include <iostream.h>

class Distance //English Distance class

{ int feet;

float inches;

public:

void getdist() //get length from user

{

cout << “\nEnter feet: “;

cin >> feet;

cout << “Enter inches: “;

cin >> inches;

}

void showdist()

//display distance

{

cout << feet << “\’-” << inches << ‘\”;

}

};

int main()

{

Distance dist;

//define a named Distance object

dist.getdist();

//access object members

dist.showdist();

// with dot operator

Distance* distptr;

//pointer to Distance

distptr = new Distance;

//points to new Distance object

distptr->getdist();

//access object members

distptr->showdist();

// with -> operator

cout << endl;

return 0;

}

Copy Constructor• A copy constructor is used to declare and initialize an object from

another object.

• For example, integer l2 (l1) ;

would define the object I2 and at the same time initialize to the

values of I1.

• Another form of this statement is

integer l2 = l1;

• The process of initializing through a copy constructor is known as

copy initialization.

• The statement. l2 = l1; will not invoke the copy constructor.

• If I1 and I2 are objects, this statement is legal simply assigns the

values of I1 to I2, member-by member.

• When no copy constructor is defined the compiler supplies its

own copy constructor

#include <iostream.h>

class code

{

int id;

public:

code ( ) { } // constructor

code(int a) // constructor again

{

id = a;

}

code (code & x)

// copy constructor

{

id = x.id;

// copy in the value

}

void display (void)

{

cout << id;

}

};

main ( )

{

code A =(100);

// object A is created an initialized

code B (A);

// copy constructor called

code C = A;

// copy constructor called again

code D;

// D is created, not initialized.

D = A;

// copy constructor not called

cout << “\n id of A: “;A. display ( );

cout << “\n id of B: “; B. display ( );

cout << “\n id of C: “; C. display ( );

cout << “\n id of D: “; D. display ( );

}

To calculate factorial of a given number using

copy constructor.

#include<iostream.h>

#include<conio.h>

class copy

{

int var,fact;

public:

copy(int temp)

{

var = temp;

}

double calculate()

{

fact=1;

for(int i=1;i<=var;i++)

{

fact = fact * i;

}

return fact;

}

};

void main()

{

clrscr();

int n;

cout<<"\n\tEnter theNumber : ";

cin>>n;

copy obj(n);

copy cpy=obj;

cout<<"\n\t"<<n<<" Factorial is:"<<obj.calculate();

cout<<"\n\t"<<n<<" Factorial is:"<<cpy.calculate();

getch();

}

• Output:

• Enter the Number: 5

• Factorial is: 120

• Factorial is: 120

Array of Objects• An array having class type elements is known as Array of

objects.

• An array of objects is declared after the class definition is

over and it is defined in the same way as any other type of

array is defined.

• For example - class item

• { public: int itemno;

• float price;

• void getdata (int i, float j) };

• item order[10];

• Here the array order contains 10 objects.

#include<iostream.h>

#include<conio.h>

class rec

{

private:

int l;

int b;

public:

rec(int a,int c)

{

I=a;

b=c;

}

void put()

{

cout<<"Area is :"<<I*b

<<endl;

}

void main()

{

clrscr();

rec obj[3]={rec(3,6),rec(2,5), rec(5,5)};

cout<<"Displaying Areas of

Rectangles : \n";

for(int i=0;i<3;i++)

obj[i].put();

getch();

}

OPERATOR OVERLOADING• Overloading means assigning different meaning to an

operation depending on the context.

• C++ permits overloading of operators, and allows to assign

multiple meanings to the operators.

• Example:-

• The input/output operators >>and << are good examples of

operator overloading

• Although the built in definition of the << (insertion) operator

is for shifting of bits.

• It is also used for displaying the values of various data types.

Contd…

Following operators can not be overloaded:-

1. Class member access operators (., . *)

2. Scope resolution operator (: :)

3. Size of operator (sizeof)

4. Conditional operator (?:)

Defining operator overloading � i) The general form is

Keyword operator to be overloaded

Return type classname :: operator operator symbol (arg list)

{

Function body //task defined

}

Where return type is the type of value returned by the

specified operation and op is the operator being overloaded.

Operator is the function name.

• #include <iostream.h>

• class temp

• {

• int count;

• public:

• temp()

• {

• count=5;

• }

• void operator ++()

• { count=count+1;

• }

• void Display()

• { cout<<"Count: "<<count;

• }

• };

• void main()

• {

• temp t;

• ++t;

• /* operator function void operator ++() is called */

• t. Display();

• getch();

• }

• Count: 6

#include <iostream.h>

#include <conio.h>

class time

{ int hrs, mins;

public:

time() { }

void getdata()

{

cout<<"Enter value for Hours : ";

cin>>hrs;

cout<<"Enter value for Minutes: ";

cin>>mins;

}

void display()

{ cout<<"\n\nHours : "<<hrs;

cout<<"\nMinutes : "<<mins;

}

operator int()

{

int t;

t = hrs*60;

t = t + mins;

return t;

}

};

void main()

{ clrscr();

time tm1;

tm1.getdata();

tm1.display();

int duration;

duration=tm1;

cout<<"\nDuration : "<<duration<<" minutes";

getch();

}

Defining operator overloading

ii) Operator functions must be either member functions or

friend function.

� The difference is a friend function will have only one

argument for unary operator and two for binary operators.

� While a member function has no arguments for unary

operators and only one for binary operators.

� This is because the object used to invoke the member

function is passed implicitly and therefore is available for the

member function.

� This is not case with friend function, because arguments

may be passed either by value or by reference

Defining operator overloading iii) Example

Vector operator - ( ) ; // unary minus

Vector operator + (vector); // vector addition

Friend vector operator + (vector, vector) // vector addition

Friend vector operator - (vector); // unary minus

Vector operator - (vector & a); // subtraction

int operator == (vector); // comparision

Friend int operator == (vector,vector) //comparision

Defining operator overloading iv) The process of overloading involves .

� Create a class that defines the data type that is to be used in

the overloading operation.

� Declare the operator function operator op () in the public

part of the class. It may be either a member or friend

function.

� Define the operator function to implement the required

operation.

Defining operator overloading v) Overloaded operator functions can be invoked by

expressions such as.

� Op x or x op For unary operators and

� x op y For binary operators.

� op x would be interpreted as

operator op (x) for friend functions

� x op y would be interpreted as

x.operator op (y) in member function and

operator op (x,y) in friend function.

RULES FOR OVERLOADING OPERATORS .

1] Only existing operators can be overloaded. New operators

cannot created.

2] The overloaded operator must have at least one operand

that is of user-defined type.

3] We cannot change the basic meaning of an operator. That is,

we cannot redefine the plus (+) operator to subtract one

value from the other.

4] Overloaded operators follow the syntax rules of the original

operators.

5] There are some operators that cannot be overloaded.

Contd…

7] Binary operators overloaded through a member function

take one explicit argument and those which one overloaded

through a friend function take two

8] When using binary operators overloaded through a

member function, the left hand operand must be an object of

the relevant class.

9] Binary arithmetic operators such as +, - *, and / must

explicitly return a value.

They must not attempt to change their own arguments.

UNARY OPERATOR OVER LOADING

i) In overloading unary operator, a friend function will have

only one argument, while a member function will have no

arguments.

ii) Let us consider the unary minus operator. A minus

operator, when used as a unary takes just one operand.

iii) This operator changes the sign of an operand when

applied to a basic data item.

# include <iostream.h>

class unary

{

int x, y, z;

public:

void getdata (int a, int b , int c);

void display (void);

void operator - (); // overload unary minus.

};

void unary :: getdata (int a, int b, int c)

{

x = a;

y = b;

z = c;

}

void unary : : display (void)

{

cout<<“The values are” <<endl;

cout << x << y << z ;

}

void unary ::operator -()

{

x = -x ;

y = -y ;

z = -z ;

}

main ( )

{

unary u;

u.getdata(20, -30, 40);

cout << “ u : “ ;

u. display ( ) ;

-u;

cout << ”u : “ ;

u. display ( ) ;

}

output: -

u : 20 -30 40

u : -20 30 -40

• # include <iostream.h>

• #include<conio.h>

• class unary

• {

• int x, y, z;

• public:

• void getdata (int a, int b , intc);

• void display (void);

• void operator !(); // overload unary minus.

• };

• void unary :: getdata (int a, intb, int c)

• {

• x = a;

• y = b;

• z = c;

• }

• void unary :: display (void)

• {

• cout<<"\tThe values are\t\n" <<endl;

• cout<<"\n\t";

• cout<<x;

• cout<<"\t";

• cout<<y;

• cout<<"\t";

• cout<<z ;

• }

• void unary ::operator !()

• {

• x = -x ;

• y = -y ;

• z = -z ;

• }

• main ( )

• {

• clrscr();

• unary u;

• u.getdata(20, -30, 40);

• cout << "\n\t u : " ;

• u. display ( ) ;

• !u;

• cout << "\n\tu : " ;

• u. display ( ) ;

• getch();

• }

iv) The function operator - ( ) takes no argument because this

function is a member function of the same class, it can

directly access the member of the object which activated it.

v) It is possible to overload a unary minus operator using a

friend function as

follows :

Friend void operator - (unary & u);

Void operator - (unary & u)

{

u.x = -u.x;

u.y = -u.y;

u.z = -u.z;

}

BINARY OPERATOR OVERLOADING

i) In overloading binary operator, a friend function will have

two arguments, while a member function will have one

argument.

ii) Following example shows how to overload + operator to add

2 complex number

# include<iostream.h>

class complex

{

float x, y;

public :

complex ( );

complex (float real, float imag)

{

x = real;

y = imag;

}

complex operator +(complex);

void display(void);

};

complex complex :: operator+

(complex c)

{

complex temp;

temp.x = x + c.x;

temp.y = y + c.y;

return (temp);

}

void complex : : display (void)

{

cout << x << “ + j “<< y << “\n “;

}

main ( )

{

complex c1,c2,c3;

c1 = complex (2.5, 3.5);

c2 = complex (1.6, 2.7);

c3 = c1 + c2;

//c1.operator +(c2);

cout << “c1 = “; c1.display( ) ;

cout << “c2 = ”; c2.display( ) ;

cout << “c3 = “; c3.display( ) ;

}

output: -

c1 = 2.5 + j 3.5

c2 = 1.6 + j 2.7

c3 = 4.1 + j 6.2

+ Operator overloading#include <iostream.h>

#include<conio.h>

class abc {

int m1,m2;

public:

abc() {}

abc(int mark1, int mark2)

{

m1 = mark1;

m2 = mark2;

}

void show()

{ cout<<" mark1 is" <<m1<<endl;

cout<< "mark2 is" <<m2<<endl;

} abc operator+(abc op2);

};

// Overload + for abc.

abc abc::operator + (abc op2)

{

abc temp;

temp.m1 = m1 +op2. m1;

temp.m2 = m2 +op2. m2;

return temp;

}

void main()

{

clrscr();

abc add1(70, 60), add2(85, 50),add;

add1.show(); // displays 70 60

add2.show(); // displays 85 50

add = add1 + add2;

add.show(); // displays addition

getch();

}

+ Operator overloading using friend#include <iostream.h>

#include<conio.h>

class abc {

int mark1, mark2;

public:

abc() {}

abc(int m1, int m2)

{

mark1 = m1;

mark2 = m2;

}

void show()

{ cout<<" mark1 is" <<mark1<endl;

cout<<"mark2 is" <<mark2<endl ;

} friend abc operator +(abc op1,abc

op2);

};

• abc operator + (abc op1,abc op2)

• {

• abc temp;

• temp.mark1 = op1.mark1 + op2.mark1;

• temp.mark2 = op1.mark2 + op2.mark2;

• return temp;

• }

• void main()

• {

• abc add1(70, 60), add2(85, 50);

• add1.show(); // displays 70 60

• add2.show(); // displays 85 50

• add1 = add1 + add2;

• add1.show(); // displays addition

• getch();

• }

Overloading prefix and postfix notation

• Standard C++ allows to explicitly create separate prefix and

postfix versions of the increment or decrement operators.

• To accomplish this, versions of the operator++( ) function are

defined. like this:

loc operator++(int x);

• The general forms for the prefix and postfix ++ and – –

operator functions.

// Prefix increment

type operator++( ) {

// body of prefix operator

}

// Postfix increment

type operator++(int x)

{

// body of postfix operator

}

// Prefix decrement

type operator– –( )

{

// body of prefix operator

}

// Postfix decrement

type operator– –(int x)

{

// body of postfix operator

}

#include<iostream.h>

#include<conio.h>

class complex

{

int a,b,c;

public:

complex(){}

void getvalue()

{

cout<<"Enter the Two Numbers:";

cin>>a>>b;

}

void operator ++()

{

a=++a;

b=++b;

}

void operator --()

{

a=--a;

b=--b;

}

void display()

{

cout<<a<<"+\t"<<b<<"i"<<endl;

}

};

void main()

{

clrscr();

complex obj;

obj.getvalue();

obj++;

cout<<"Increment Complex

Number\n";

obj.display();

obj--;

cout<<"Decrement Complex

Number\n";

obj.display();

getch();

}

Output:

Enter the two numbers:

3

6

Increment Complex Number

4 + 7i

Decrement Complex Number

3 + 6i

Friend to Overload ++ or – –#include <iostream.h>

class stu

{

int rollno, idno;

public:

stu() {}

stu (int rn, int id)

{

rollno = rn;

idno = id;

}

void show()

{

cout <<“rollno

is”<<rollno<<endl ;

cout << “idno is”<<idno "\n";

}

friend stu operator++(stu &op);

friend stu operator--(stu &op);

};

stu operator ++(stu &op)

{

op.rollno++;

op.idno++;

return op;

}

stu operator--(stu &op)

{

op.rollno--;

op.idno--;

return op;

}

int main()

{

stu ob1(10, 20), ob2;

ob1.show();

++ob1;

ob1.show(); // displays 11 21

ob2 = ++ob1;

ob2.show(); // displays 12 22

--ob2;

ob2.show(); // displays 11 21

return 0;

}

Overloading of + operator to concatenate two strings

#include<iostream.h>

#include<conio.h>

#include<string.h>

class string

{

char str[100];

public:

void input();

void output();

string operator+(string s);

};

void string::input()

{ cout<<"enter the string\n";

gets(str);

}

void string::output()

{

cout<<"the string is\n";

cout<<str;

}

string string::operator+(string s)

{

string temp;

strcpy (temp.str,s.str);

strcat(temp.str,s.str);

return(temp);

}

void main()

{

string s1,s2,s3;

clrscr();

s1.input();

s2.input();

s3=s1+s2;

s3.output();

getch();

}

• enter the string : abc

enter the string : xyz

the string is : abcxyz

Overloading [ ]

• In C++, the [ ] is considered a binary.

• The general form of a member operator[ ]( ) function is as

shown here:

• type class-name::operator[] (int i)

{

// . . .

}

• Technically, the parameter does not have to be of type int,

but an operator[ ]( ) function is typically used to provide

array subscripting, and as such, an integer value is

generally used.

• Given an object called O,

the expression O[3] translates into this call to the

operator[ ]( ) function:

• O.operator[](3)

• That is, the value of the expression within the subscripting

operators is passed to the operator[ ]( ) function in its

explicit parameter.

• The this pointer will point to O, the object that generated

the call

#include <iostream.h>

class atype

{

int a[3];

public:

atype(int i, int j, int k)

{

a[0] = i;

a[1] = j;

a[2] = k;

}

int operator[](int i)

{

return a[i];

}

};

int main()

{

atype ob(1, 2, 3);

cout << ob[1]; // displays 2

return 0;

}

Overloading << and >> operator#include <iostream.h>

class Distance

{

private: int feet;

int inches;

Public

Distance()

{ feet = 0; inches = 0;

}

Distance(int f, int i)

{ feet = f; inches = i;

}

friend ostream &operator<<

( ostream &output, const Distance &D )

{

output << "F : " << D.feet << " I : " << D.inches;

return output;

}

friend istream &operator>>( istream &input, Distance &D )

{

input >> D.feet >> D.inches; return input;

}

};

int main()

{

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

cout << "Enter the value of object : " << endl;

cin >> D3;

cout << "First Distance : " << D1 << endl;

cout << "Second Distance :" << D2 << endl;

cout << "Third Distance :" << D3 << endl;

return 0;

}

• Enter the value of object : 70 10

• First Distance : F : 11 I : 10

• Second Distance :F : 5 I : 11

• Third Distance :F : 70 I : 10