Jump to content

Passing object by reference

- - - - -

  • Please log in to reply
2 replies to this topic

#1
ThemePark

ThemePark

    Programmer

  • Members
  • PipPipPipPip
  • 124 posts
I have the following code:
/*
 * Test.h
 *
 *  Created on: 03/12/2010
 *      Author: Mikaeru
 */

#ifndef TEST_H_
#define TEST_H_

#include <iostream>
using namespace std;

class Test {
private:
    int j;

public:
    Test(int i);
    void print();
    void setT(Test& t);
    void setJ(int i);
    int getJ();
};

Test t(1);
#endif /* TEST_H_ */


/*
 * Test.cpp
 *
 *  Created on: 03/12/2010
 *      Author: Mikaeru
 */

#include "Test.h"

Test::Test(int i) {
    j = i;
}

void Test::print () {
    cout << t.getJ() << endl;
}

void Test::setT(Test& test) {
    t = test;
}

void Test::setJ(int i) {
    j = i;
}

int Test::getJ() {
    return j;
}

int main(int argc, char **argv) {
    cout << "T" << endl;
    Test t(3);
    Test t2(1);
    t2.setT(t);
    t2.print();
    t.setJ(5);
    t2.print();

    return 0;
}

And I want the second t2.print() to return 5, which should work because I'm passing t by reference, but for some reason it doesn't work. Why?

#2
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1

Test* t2 = &t;

This should do it. You then access t2 methods with selector (arrow operator).

t.print();

t2->print();

t.setJ(42);

t2->print();


A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#3
ThemePark

ThemePark

    Programmer

  • Members
  • PipPipPipPip
  • 124 posts
I guess I should have been more specific. That won't work. I have a class inside which I have an object which I need to share with a second class. In this second class I modify the object in some way, and then return to the first class where the object should stay modified. It seems it should be possible with the & operator, but it won't work for some reason in my code.

Update:
I have tried debugging my code, and say that &t = 0x405020, &t2 = 0x22ff48, then I would expect that the parameter &test = 0x405020, but instead it's 0x22ff4c. And I can see that the t variable inside t2 is updated with the test parameter, but the change made with setT() isn't reflected.

Edited by ThemePark, 06 December 2010 - 05:59 AM.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users