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

Friend function (programs)

The document contains C++ code examples demonstrating the use of friend functions to access private data members of classes. It includes three examples: one that displays a number, one that adds two integers using friend functions, and a third that involves two separate classes for addition. The code is structured with class definitions, friend function declarations, and main functions to execute the operations.

Uploaded by

akankshat2007
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)
3 views

Friend function (programs)

The document contains C++ code examples demonstrating the use of friend functions to access private data members of classes. It includes three examples: one that displays a number, one that adds two integers using friend functions, and a third that involves two separate classes for addition. The code is structured with class definitions, friend function declarations, and main functions to execute the operations.

Uploaded by

akankshat2007
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

channel link : h ps://www.youtube.

com/c/ComputerScienceAcademy7
video link : h ps://youtu.be/Eb-_TA_qbhA

// Friend Func on
/*

#include<iostream.h>
#include<conio.h>

class number
{
private:
int a;
public:
void display()
{
a = 5;
cout<<"Number = "<<a;
}
friend void show();
};

void show() //independent func on


{
number N1;
N1.a = 10;
cout<<"number = "<<N1.a;

void main()
{
clrscr();

show();
number N1;
N1.a = 25;

getch();

}
*/

/*

// Addi on of two int numbers by using Friend Func on

#include<iostream.h>
#include<conio.h>

class number
{
private:
int a;
public:
void getdata(int x)
{
a = x; //N1.a = 10 N2.a = 20
}

friend int Add(number N1, number N2);

};

int Add(number N1, number N2)


{
int sum = N1.a + N2.a;
return sum;

void main()
{
clrscr();

number N1, N2;


N1.getdata(10);
N2.getdata(20);

int sum = Add(N1,N2);


cout<<"Sum = "<<sum;

getch();

}
*/

// Addi on of two int numbers by using Friend Func on

#include<iostream.h>
#include<conio.h>

class number2; //forward declara on


class number1
{
private:
int a;
public:
void getdata(int x)
{
a = x; //N1.a = 10
}

friend int Add(number1 N1, number2 N2);

};

class number2
{
private:
int a;
public:
void getdata(int x)
{
a = x; //N2.a = 20
}

friend int Add(number1 N1, number2 N2);

};
int Add(number1 N1, number2 N2)
{
int sum = N1.a + N2.a;
return sum;

void main()
{
clrscr();

number1 N1;
number2 N2;

N1.getdata(10);
N2.getdata(20);

int sum = Add(N1,N2);

cout<<"Sum = "<<sum;

getch();

You might also like