Modification in C++ Classes program through Association

hello everyone... i need some help... how can i sett and get the values in two classes through association. here is my little code that i wrote just to understand the concept of how to modify the one class attributes through association between two classes.

=========================================================
#include <iostream.h>

class Student
{
public:
Student(){}
Student(int v)
{
var = v;
}
~Student(){}
void setVar()
{
cout << "set the number: ";
cin >> var;
}
int getVar()
{
return var;
}
private:
int var;
};

class Teacher
{
public:
void setIDDDD(Student s)
{
s.setVar();
}
void getIDDDD(Student s)
{
cout <<s.getVar()<<endl;
}

private:
};

void main()
{
Student ob(41);
Teacher obj;

cout << "Set by object: " <<ob.getVar()<<endl;
ob.setVar();
cout << "Setter Value: " <<ob.getVar()<<endl;

obj.setIDDDD(ob);
obj.getIDDDD(ob);
}
==========================================================
In upper code, i am trying to set the new value in Student class through through teacher class. Setters and getters properly works and change the values with Student class object but when i set the values through Teacher class, it shows the old value sett by the Student Object.

Last edited on
you have to pass by reference, you are passing by value, so setIDDDD(Student s) is creating a local Student and modifying the value of it but its not changing the original Student you passed.

change it to setIDDDD(Student &s)

Read about pass by value, reference and pointer.
Yes ,change your function as :

void setIDDDD(Student &s)
{
s.setVar();
}
and it shld work...

Chk the below link for understanding the concept of association in C++:

http://www.go4expert.com/forums/showthread.php?t=17264
Thank you so much @alwaysLearning0 and @NewDev...

but wats the reason... why only reference works in this case, y not value as well... pls elaborate

thanks
Topic archived. No new replies allowed.