Pages

C++ Programming Tutorials -24(More on C++ Friend Functions (Examples & Explanation))

tut28.cpp=
// This tut contains More on C++ Friend Functions (Examples & Explanation) 

#include<iostream>
using namespace std;

class Y;

class X{
    int data;
    public:
        void setValue(int value){
            data = value;
        }
    friend void add(XY);    
};

class Y{
    int num;
    public:
        void setValue(int value){
            num = value;
        }
    friend void add(XY);    

};

void add(X o1Y o2){
    cout<<"Summing data of X and Y objects gives me "<< o1.data + o2.num<<endl;
}

int main(){
    X a1;
    a1.setValue(3);

    Y b1;
    b1.setValue(15);

    add(a1b1);
    return 0;
}

//-------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------


#include<iostream>
using namespace std;
class c2;

class c1{
    int val1;
    friend void exchange(c1 & , c2 &);
    public:
        void indata(int a){
            val1 = a;
        }

        void display(void){
            cout<< val1 <<endl;
        }
};

class c2{
    int val2;
    friend void exchange(c1 &c2 &);
    public:
        void indata(int a){
            val2 = a;
        }

        void display(void){
            cout<< val2 <<endl;
        }
};


// Trick to swap 2 numbers a and b:
// temp = a;
// a = b;
// b = temp;


void exchange(c1 &xc2 &y){
    int tmp = x.val1;
    x.val1 = y.val2;
    y.val2 = tmp;
}

int main(){
    c1 oc1;
    c2 oc2;

    oc1.indata(34);
    oc2.indata(67);
    exchange(oc1oc2);

    cout<<"The value of c1 after exchanging becomes: ";
    oc1.display();
    cout<<"The value of c2 after exchanging becomes: ";
    oc2.display();
    
    return 0;
}


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Top 10 Python Packages Every Developer Should Learn

Top 10 Python Packages Every Developer Should Learn There are more than  200,000 Python packages  in the world (and that’s just counting tho...