Accessing Members of Containing Objects from Contained Objects.

Posted by Bunkai.Satori on Stack Overflow See other posts from Stack Overflow or by Bunkai.Satori
Published on 2011-03-08T07:13:46Z Indexed on 2011/03/08 8:10 UTC
Read the original article Hit count: 306

Filed under:
|
|
|

If I have several levels of object containment (one object defines and instantiates another object which define and instantiate another object..), is it possible to get access to upper, containing - object variables and functions, please?

Example:

    class CObjectOne
    {
    public:
       CObjectOne::CObjectOne() { Create(); };

       void Create();

       std::vector<ObjectTwo>vObejctsTwo;
       int nVariableOne;
    }
    bool CObjectOne::Create()
    {
       CObjectTwo ObjectTwo(this);
       vObjectsTwo.push_back(ObjectTwo);
    }

    class CObjectTwo
    {
     public:
       CObjectTwo::CObjectTwo(CObjectOne* pObject)
       {
        pObjectOne = pObject;
        Create();
       };

       void Create();
       CObjectOne* GetObjectOne(){return pObjectOne;};

       std::vector<CObjectTrhee>vObjectsTrhee;
       CObjectOne* pObjectOne;
       int nVariableTwo;
    }
    bool CObjectTwo::Create()
    {
       CObjectThree ObjectThree(this);
       vObjectsThree.push_back(ObjectThree);
    }

    class CObjectThree
    {
     public:
       CObjectThree::CObjectThree(CObjectTwo* pObject)
       {
        pObjectTwo = pObject;
        Create();
       };

       void Create();
       CObjectTwo* GetObjectTwo(){return pObjectTwo;};

       std::vector<CObjectsFour>vObjectsFour;
       CObjectTwo* pObjectTwo;
       int nVariableThree;
    }
    bool CObjectThree::Create()
    {
       CObjectFour ObjectFour(this);
       vObjectsFour.push_back(ObjectFour);
    }

main()
{
    CObjectOne myObject1;
}

Say, that from within CObjectThree I need to access nVariableOne in CObjectOne. I would like to do it as follows:

int nValue = vObjectThree[index].GetObjectTwo()->GetObjectOne()->nVariable1;

However, after compiling and running my application, I get Memory Access Violation error.

  • What is wrong with the code above(it is example, and might contain spelling mistakes)?
  • Do I have to create the objects dynamically instead of statically?
  • Is there any other way how to achieve variables stored in containing objects from withing contained objects?

© Stack Overflow or respective owner

Related posts about c++

Related posts about oop