Search code examples
c++friend

Setting a value by a friend function which is a member function of another class


setwidth() is a member function of class Box and it is also a friend function of class Sbox which is setting the values of members width of both classes.

The value of width of the class Sbox is not setting/coming out properly.

#include<iostream>

using namespace std;

class Sbox;

class Box{
    private:
        double width;
    public:
        friend void printwidth(Box box);
        void setwidth(Sbox sbox, double wid);
};

class Sbox {
    private:
        double width;
    public:
        friend void Box::setwidth(Sbox sbox, double wid);
        void printwidth() {
            cout << "the width of small box: " << width; //this value is coming wrong
        }
};

void Box::setwidth(Sbox sbox, double wid) {
    width = wid;
    sbox.width = wid;
}

void printwidth(Box box) {
    cout << "width of the box: " << box.width << endl;
}

int main() {
    Box box;
    Sbox sbox;
    box.setwidth(sbox, 10.77);
    printwidth(box);
    sbox.printwidth();
    return 0;
}

Solution

  • You need to pass the Sbox in by reference. Add the ampersand to these three lines.

    void setwidth(Sbox& sbox,double wid);

    friend void Box::setwidth(Sbox& sbox,double wid);

    void Box::setwidth(Sbox& sbox,double wid)

    You were passing your sbox in by value, which means that a copy is made for use inside setwidth. Your code then changes the width on that copy of sbox, but the copy is then destroyed at the end of setwidth, and the original sbox outside the function remains unchanged.

    Adding the & means that the Sbox argument is passed by reference, which means that a copy is never made, and so the sbox inside setwidth is the same object as the one outside.

    Have a read here: How to pass objects to functions in C++?