Rahul
Rahul

Reputation: 277

Returning const reference from function

I want my function to return an array of objects. But i want some restriction on returned reference so that returned value/reference is not modified by caller.

Eg

class A
{
    B **arrB;

    public :
        A() 
        {
            initialize arrB 
        }
        B** getB()
        {
           return arrB;
        }
}

In above code, array returned by getB() function, should not be modified. Can someone suggest best way to do this ? Can "const" help?

Upvotes: 2

Views: 229

Answers (4)

esskar
esskar

Reputation: 10940

const doesn't really help. The compiler may raise some warnings/errors when you try to modify the array, but you can always cast to a non-const pointer and modify it. const is more a hint to the user of the class: the pointer I'm giving you you is read-only; modify it at your peril!

Upvotes: 1

Ivo Peterka
Ivo Peterka

Reputation: 31

Well, the possible way I see is to return new array copied from the private one (containing copies of original object instances). If you want to be sure the private member of the class is not changed you then need not to care about what the code which takes the copy of arrB pointer will do with it. But of course there are disadvantages like more memory usage and that the consumer has to delete obtained array.

Upvotes: 1

AndersK
AndersK

Reputation: 36082

this should do it:

const B * const * getB() const { return arrB; }

EDIT: added const since member function doesn't modify contents.

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409166

Yes it will help. But then you will get an error about illegal conversion from B ** to const B **, but that is the reason for const_cast:

const B** getB() const
{
    return const_cast<const B**>(arrB);
}

Note that I added an extra const qualifier after the function declaration. This tells the compiler that the function does not modify anything in the class.

Upvotes: 3

Related Questions