This is my sample program
#include "stdafx.h"
class B
{
public:
int i,j;
};
class A
{
public:
B b[2];
A()
{
b[0].i = 1;
b[0].j = 2;
b[1].i = 3;
b[1].j = 4;
}
B* function()
{
return b;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
A a;
B* obj = new B();
obj = a.function();
return 0;
}
I have to get the array of b objects(ie, need all the values, b[0].i, b[0].j,b[1].i and b[1].j)
But when I tried it with this code, only one object is returned.
What you state in the question is not true. Two objects are indeed returned. Access them with
obj[0]andobj[1].I guess you are looking at
objunder the debugger and the IDE cannot know that you mean for your pointerobjto be an array of two objects. So the tooltips will only show the first object,obj[0], or*obj. But the other object,obj[1]is definitely there.Add the following line after the call to
a.function:and you will see this output:
Note that there is no point in the line
B* obj = new B();since you immediately overwriteobj. You should do it this way:Your code is also a little dangerous in that you must keep
aalive at least as long as you are making references toobj.