Returning references (scope problems?)

This is a discussion on Returning references (scope problems?) within the C++ Programming forums, part of the General Programming Boards category; In an old C++ book I have, the following example is given for overloading the [] operator: int &IntArray::operator[] (int ...

  1. #1
    Registered User
    Join Date
    Dec 2001
    Posts
    15

    Returning references (scope problems?)

    In an old C++ book I have, the following example is given for overloading the [] operator:

    int &IntArray::operator[] (int index)
    {
    static int dummy=0;
    if((index=0) && (index < length))
    return array[index];
    else
    {
    cout << "Error: index out of range.\n";
    return dummy;
    }
    }

    where length and array[] are member variables of the class IntArray.

    My question is as follows. Suppose you have this code:

    int x;
    {
    IntArray somearray;
    x=somearray[0];
    }
    Dosomethingwith(x);

    Since somearray[0] returns a reference to data in somearray and somearray goes out of scope before x does, wont bad things happen when Dosomethingwith() tries to use x?

  2. #2
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    dummy is a static variable. When static variables go out of scope they still exist in memory (they're not allocated on the stack), so it is legal to return a reference to one.
    zen

  3. #3
    Registered User
    Join Date
    Dec 2001
    Posts
    15
    Right, but I'm talking about

    return array[index];

    not

    return dummy;

  4. #4
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    Sorry, yes bad things will happen in your second example. The first is OK though as array is presumably a class member and not local to the operator[] function.
    zen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems returning char *
    By Necromancer in forum C Programming
    Replies: 10
    Last Post: 01-30-2008, 11:28 AM
  2. Problems with returning a char* to fprint.
    By qubit67 in forum C Programming
    Replies: 5
    Last Post: 08-09-2007, 12:28 AM
  3. C Pointers Problems
    By mhelal in forum C Programming
    Replies: 8
    Last Post: 01-10-2007, 06:35 AM
  4. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  5. DJGPP problems
    By stormswift in forum C Programming
    Replies: 2
    Last Post: 02-26-2002, 04:35 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21