Call by Referenc with this as Referenc

Hi,

I have a question. I would like to get the this pointer by call by reference. Is this possible? I hoped to get it with this code, but it doesn't work:
[code="cpp"]class DemoClass
{
public:
DemoClass();
int x;
void setParam(const DemoClass &param){
param=this;
}
};

int main(int argc, char *argv[])
{
DemoClass *test1,*test2;
test1->x=1;
test2->x=2;
test1->setParam(*test2);
qDebug() << test1->x;
qDebug() << test2->x;
};
[/code]

I get alwayes the error code "C2678". But I don't understand how I should change my code to avoid this.

bg,
flambert
this is a special kind of pointer type. Try dereferencing it ie:param=*this

Aceix.
You're simply trying to assign to a 'const' declared parameter. Remove 'const' and everything should work well.

(But better assign some memory to your test1 and test2 variables first...)



EDIT: Added comment in parenthesis.
Last edited on
After some more trials I have this code. But I have still the same problem. I would expect, that my second output is "99" but it is still "1":
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class DemoClass
{
public:
    DemoClass();
    int x;
    void setParam(DemoClass &param);
};

DemoClass::DemoClass()
{

}

void DemoClass::setParam(DemoClass &param)
{
    param=*this;
}




int main(int argc, char *argv[])
{
    DemoClass *test1 = new DemoClass();
    DemoClass *test2 = new DemoClass();
    test1->x=1;
    test2->x=2;
    test1->setParam(*test2);
    qDebug() << test1->x;
    test1->x=99;
    qDebug() << test2->x;

}
test2 is now a copy of test1. Both are different objects as before. test2 just got the attributes assigned from test1.
Topic archived. No new replies allowed.