PDA

View Full Version : C++ pointer by reference problem.



dragonKlavier
19th April 2016, 00:02
Hello.

I have problems with pointers by reference topic. This is the isue:

I have in a qt program:

- One class "A" with a class "B" and "C" instanced inside.
- A class D. This constains a set of Strings. And it is declared as a data member in "A" ,"B" and "C".


The problem is that I have to modify the "D" values (I have an instance of D class in A ,B and C) in any of the three classes and I need to manage a same value.

So, I think:



Class A.
{
B * m_b;
C * m_c;
D * m_d;


A()
{
m_b= new B(&m_d);
m_c= new C(&m_d);
}
}

Class B.
{
D* m_d;

B(D* &d)
{
m_d=d
}
}



Class C.
{
D* m_d;

C(D* &d)
{
m_d=d
}
}




My problem is that before y create m_d in B, I cant see the address in m_d of C.

Plese...I need your help

Thanks a lot!

anda_skoa
19th April 2016, 10:42
If you only need to modify the values of the D instance, you can simply pass pointers to the D instance.
You only need a reference to the pointer if you need to change the pointer itself.

Just create the D instance before you create the B and C instance.

Cheers,
_

dragonKlavier
20th April 2016, 19:51
thanks to all of you!!

My problem were....I passed the pointer by reference before I declared it.. lol..XD!

The only unusual issue is that the compiler give not me an error.

Thaks!!