Lecture 6
Lecture 6
Friend Function
Copy constructor
1
Friend Function
A friend function is a function that is not a member of a class but has access to the
class's private and protected members. Friend functions are not considered class
members; they are normal external functions that are given special access privileges.
Programming Example:
#include <iostream>
using namespace std;
class Distance
{
private:
int meter;
public:
friend int func(Distance d);
};
int func(Distance d)
{
d.meter=5;
return d.meter;
}
int main()
{
Distance D;
cout<<"Distace: "<<func(D);
return 0;
}
Friend Function Example
#include <iostream> void printWidth( Box box )
using namespace std; {
class Box cout << "Width of box : " <<
box.width <<endl;
{
}
double width;
int main( )
public: {
friend void printWidth( Box box ); Box b;
void setWidth( double wid ); b.setWidth(10.0);
}; printWidth( b);
// Member function definition return 0;
void Box::setWidth( double wid ) }
{
Output:
width = wid;
Width of box : 10
}
What are the characteristics of friend functions?
A friend function is not in the scope of the class in which it has been declared as friend.
int main() {
class Example {
Example Object(10,20);
int a,b;
public: //Copy Constructor
Example(int x,int y) { Example Object2=Object;
a=x;
b=y;
// Constructor invoked.
cout<<"\nIm Constructor";
} Object.Display();
Object2.Display();
void Display() {
cout<<"\nValues :"<<a<<"\t"<<b;
return 0;
}
}; }
copy constructor Example
#include <iostream> int main( )
using namespace std;
{
class cc
{ cc ob(100);
int a; cc ob1(ob);
public: ob.show();
cc(int x){
ob1.show();
a=x;
}
}
void show(){
cout<<"a="<<a<<endl;
}
cc(cc &o){
a=o.a;
}
};
Deep Copy
#include <iostream> void set(int m){
*x=m;
using namespace std;
}
class A{
private: void show(){
int *x; cout<<*x<<endl;
}
public:
};
A(int p){
x=new int; int main()
*x=p; {
A ob(10);
A ob1=ob;
} ob.show();
A( A & obj) ob1.show();
{ ob1.set(20);
ob.show();
ob1.show();
x = new int;
*x = *(obj.x); return 0;
} }