|
-
April 18th, 2016, 05:13 PM
#1
Pointer by reference problem
Hello.
I have problems with pointers by reference topic. This is the isue:
I have:
- 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:
Code:
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!
-
April 19th, 2016, 12:30 AM
#2
Re: Pointer by reference problem
 Originally Posted by dragonklavier
My problem is that before y create m_d in B, I cant see the address in m_d of C.
I don't see how that is a problem: both m_d pointers in the B and C objects point to the same D object. Your problem is that you did not create this D object, and then you made a type mistake, i.e., &m_d is a D**, but you wanted to pass a D* to the constructors of B and C. Personally, I don't need why you need dynamic memory allocation here, so if I were you, I would go for something like:
Code:
class D
{
// ...
};
class B
{
public:
B(D* d) : m_d(d) {}
private:
D* m_d;
};
class C
{
public:
C(D* d) : m_d(d) {}
private:
D* m_d;
};
class A
{
public:
A() : m_d(/* whatever */), m_b(&m_d), m_c(&m_d) {}
private:
D m_d;
B m_b;
C m_c;
};
I took care to declare m_d first in A in case the constructors of B and C should want to do something with the D object.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|