CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Pointer by reference problem

  1. #1
    Join Date
    Apr 2016
    Posts
    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!

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,768

    Re: Pointer by reference problem

    Quote 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.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

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
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)