andrew Patterson
andrew Patterson

Reputation: 579

Passing an object into a class by reference

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.

Upvotes: 0

Views: 2179

Answers (2)

Damian
Damian

Reputation: 4641

You can hold a member variable of class2 in class1 like this and have a set variable set the member variable.

#include <iostream>

using namespace std;

class class2 
{
public:
    int m_i;
};

class class1 
{
public:
    void set(class2& c2) { m_c2 = c2; };
    class2 m_c2;
};

void main()
{
    class2 c2;
    c2.m_i = 2;

    class1 c1;
    c1.set(c2);

    cout << c1.m_c2.m_i << std::endl;

}

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168726

struct class2 {
  int i, j;
};
struct class1 {
  class2& c2;
  class1(class2& c2) : c2(c2) {}
  void Froz() {
    c2.i = c2.j;
  }
  int Baz() {
    return c2.i * c2.j;
  }
};


EDIT: In your example, in the relatedclass constructor, you take the address of a local variable. That variable will be destroyed when the constructor returns. After that, your pmc pointer points to a destroyed object, which is a no-no.

Change this line:

relatedclass(myclass ob)

to this

relatedclass(myclass& ob)

Upvotes: 1

Related Questions