0
#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?

  • The object `x` is `getdata` is a **copy** of the object `a` in `main`. By default C++ uses *value semantics* which means that when one variable is assigned to another the new variable has a copy of the value that the old variable had. This is different from the *reference semantics* that some languages use, where assigning one variable to another means that both variables reference the same value. It's a fundamental difference and for some reason many newbies assume that C++ uses reference semantics. It does not. If you want a reference then you have to declare it `void getdata(person& x)` – john Nov 28 '22 at 06:08
  • This is a completely separate issue from friendship, which is about being able to access names in a class. In your code friendship is working because you can access the private names `person::name` and `person::age` in `getdata` without getting a compiler error. – john Nov 28 '22 at 06:09

1 Answers1

1

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;.

bitmask
  • 32,434
  • 14
  • 99
  • 159