0

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.

2
  • How do you know one object is returned? Commented Feb 29, 2012 at 16:34
  • What's that new B() doing there? All it does is add a memory leak. Commented Feb 29, 2012 at 16:53

3 Answers 3

1

What you state in the question is not true. Two objects are indeed returned. Access them with obj[0] and obj[1].

I guess you are looking at obj under the debugger and the IDE cannot know that you mean for your pointer obj to 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:

printf("%d, %d, %d, %d\n", obj[0].i, obj[0].j, obj[1].i, obj[1].j);

and you will see this output:

1, 2, 3, 4

Note that there is no point in the line B* obj = new B(); since you immediately overwrite obj. You should do it this way:

B* obj = a.function();

Your code is also a little dangerous in that you must keep a alive at least as long as you are making references to obj.

Sign up to request clarification or add additional context in comments.

Comments

1

This code

B* function()
        {
          return b;
        }

returns the pointer to the first element of array

B b[2];

which can be dereferenced applying pointer arithmetics and/or operator [].

Comments

1

Yes, you are actually returning the a pointer to the array b[2]. What you want to do now is to iterate through the items in that pointer. You can print them by adding this lines to you code:

A a;
B *obj = a.function();
std::cout << obj[0].i << ", " << obj[0].j << "; " << obj[1].i << ", " << obj[1].j << std::endl;

And of course, including iostream at the beginning of your file:

#include <iostream>

2 Comments

B* obj = new B() is totally unnecessary here, it can be simple B* obj = a.function() else there will be memory leak.
Editted that. Anyway, it was not what he was asking(although it's a valid correction).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.