Right Ill try to explain my thinking here.
I have two classes at the moment, known as class1 and class2.
I want to pass an object of class2 into an object of class1, by reference.
but i want to only have to pass it in once, rather than having to pass it in every time a method is called.
I’ve tried creating a pointer and I have tried creating a reference, but to no avail.
Any help appreciated.
#include <iostream>
using namespace std;
class myclass
{
private:
int i;
public:
myclass()
{
}
void method()
{
cout << "Enter num: ";
cin >> i;
}
void display()
{
cout << i;
}
};
class relatedclass
{
public:
relatedclass(myclass ob)
{
pmc = &ob;
}
myclass *pmc;
};
void main()
{
myclass mc;
relatedclass rc(mc);
//display value of mc.i
mc.display();
cout << endl;
//ok lets change the i variable
rc.pmc->method();
cout << endl;
//display new value of mc.i
mc.display();
cout << endl;
}
for the test date I entered 50, and i expected the mc object to be updated and i would now equal 50.
EDIT: In your example, in the
relatedclassconstructor, you take the address of a local variable. That variable will be destroyed when the constructor returns. After that, yourpmcpointer points to a destroyed object, which is a no-no.Change this line:
to this