Q:write a CPP program to declare 3 classes perform the addition of the data members in first 2 classes and result in the 3rd class using friend function
DEFINITION:
friend function:In object-oriented programming, a friend function that is a "friend" of a given class is allowed access to private and protected data in that class that it would not normally be able to as if the data was public . Normally, a function that is defined outside of a class cannot access such information.
PROGRAM:
#include <iostream>
#include<conio.h>
using namespace std;
void add();
class A{
int a[10],limit;
public:
A(int m){
limit=m;
cout<<"enter array"<<endl;
for(int i=0;i<limit;i++)
cin>>a[i];
}
friend void add();
};
class B{
int a[10],limit;
public:
B(int m){
limit=m;
cout<<"enter array"<<endl;
for(int i=0;i<limit;i++)
cin>>a[i];
}
friend void add();
};
class C{
int a[10],limit;
public:
C(){
limit=0;
}
friend void add();
void addToC(int k){
a[limit]=k;
limit++;
}
void showC(){
for(int i=0;i<limit;i++)
cout<<a[i]<<" ";
}
};
int main()
{
add();
}
void add(){
int limit;
cout<<"limit:";
cin>>limit;
A a(limit);
B b(limit);
C c;
for(int i=0;i<limit;i++)
c.addToC(a.a[i]+b.a[i]);
c.showC();
}
DEFINITION:
friend function:In object-oriented programming, a friend function that is a "friend" of a given class is allowed access to private and protected data in that class that it would not normally be able to as if the data was public . Normally, a function that is defined outside of a class cannot access such information.
PROGRAM:
#include <iostream>
#include<conio.h>
using namespace std;
void add();
class A{
int a[10],limit;
public:
A(int m){
limit=m;
cout<<"enter array"<<endl;
for(int i=0;i<limit;i++)
cin>>a[i];
}
friend void add();
};
class B{
int a[10],limit;
public:
B(int m){
limit=m;
cout<<"enter array"<<endl;
for(int i=0;i<limit;i++)
cin>>a[i];
}
friend void add();
};
class C{
int a[10],limit;
public:
C(){
limit=0;
}
friend void add();
void addToC(int k){
a[limit]=k;
limit++;
}
void showC(){
for(int i=0;i<limit;i++)
cout<<a[i]<<" ";
}
};
int main()
{
add();
}
void add(){
int limit;
cout<<"limit:";
cin>>limit;
A a(limit);
B b(limit);
C c;
for(int i=0;i<limit;i++)
c.addToC(a.a[i]+b.a[i]);
c.showC();
}
No comments:
Post a Comment