Hack Forums
[C] Accessing an object's private integer array. - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C] Accessing an object's private integer array. (/showthread.php?tid=5002028)



Accessing an object's private integer array. - DeafConn - Sep 27, 2015

Hello everyone. So I'm working with a class that has a private member variable that is an integer array of size 4. Here is the code for it:
http://pastebin.com/i9u5DtUi - MoveRate.h
http://pastebin.com/q1xd61VQ - MoveRate.cpp

Now if one looks at the code they can execute the following snippets:
PHP Code

<?php 
//The declaration of the object in the private field of a header
private:
MoveRate m_moveRate;

//A getter to access the private object
MoveRate DirectionSim::getMoveRate(){
    return 
m_moveRate;
}

//Finally, a snippet to actually modify the private integer array.
getMoveRate().setAMoveRate(2, 0);
cout << "COMP: "<< getMoveRate().getAMoveRate()[0] << endl; 

Now, looking at the MoveRate.cpp, I have placed debug code in the setter for the A array. Running this program should give the following output:
Code
VAL: 2 ACT: 2
COMP: 2

Instead, I get this:
Code
VAL: 2 ACT: 2
COMP: 473122

Can anyone explain this behavior? Thanks.


* - bbbysmth - Sep 27, 2015

You release that you have to create the object and save the instance in a variable to access it later right?


* - DeafConn - Sep 27, 2015

(Sep 27, 2015 07:18 AM)bbbysmth Wrote:  You release that you have to create the object and save the instance in a variable to access it later right?

The object created was m_MoveRate. It is stored in the variable m_MoveRateA inside of the m_MoveRate object.


I managed to fix the error. for anyone else looking for the solution, you need to make the array dynamic instead.

so in the constructor do:
Code
m_moveRateA = new int[ARRAY_SIZE];