Search code examples
c++oopfriend

How to get values for the variables inside a class using a friend functions


#include <iostream>
#include <string>
using namespace std;

class person {

    string name;
    int age;

    public :
    person() {
        name = "no data found";
        age = 0;
    }

    person(string x, int y) {
        name = x;
        age = y;
    }

    friend void getdata(person);
    friend void printdata(person);
};

void getdata(person x) {
    
    cout<<"Enter name : "<<endl;
    getline(cin, x.name);
    cout<<"Enter age : "<<endl;
    cin>>x.age;
};

void printdata(person x) {
    cout<<"Name : "<<x.name<<endl;
    cout<<"Age : "<<x.age<<endl;
}

int main() {

    person a;
    getdata(a);
    person b("Raj Mishra", 17);
    printdata(a);
    printdata(b);
    return 0;
}

in the above code, even if i enter the values through the getdata(a) function the values in the default constructor show up on the console screen when the printdata(a) function runs.

This is not the case when i create an object using the constructor like when creating the object b. What do i do?


Solution

  • You have to pass the person object by reference:

    class person {
        // ...
        friend void getdata(person&);
        friend void printdata(person const&);
    };
    
    void getdata(person& x) {
        //             ^
        std::cout << "Enter name : " << std::endl;
        getline(std::cin, x.name);
        std::cout << "Enter age : " << std::endl;
        std::cin >> x.age;
    };
    
    void printdata(person const& x) {
        //                ^^^^^^
        std::cout << "Name : " << x.name << std::endl;
        std::cout << "Age : " << x.age << std::endl;
    }
    

    Also, you should not use using namespace std;.