Question:

In c // int & operator [ ] (int indx); !?

by Guest59922  |  earlier

0 LIKES UnLike

I want someone explain this line to me ???

int & operator [ ] (int indx) ;

This an operator introduced in a class in the public level .... the question is:

What does the amersand (&) sign and the empty brackets [ ] refer to?

I need explanation.

thanks

 Tags:

   Report

2 ANSWERS


  1. I'm assuming that you're overloading the operator [ ] so that you can access the indx'th value of a user-defined array class object.  What is returned is the value at indx in the array, and it's an int.

    [ ] is the array operator.

    int & means to return an int when you use the overloaded operator


  2. Basically, you're defining a function.

    int& = the return type of the function.  The function will return an int, by reference

    operator[] is the name of the function.  But it's special...you don't have to call it like myArray.operator[](5).  You can instead call it like myArray[5].  You could also define a function called operator+ but instead of calling it like myArray.operator+(someOtherArray) you'd call it like myArray + someOtherArray.

    This is called operator overloading, and you use it if you want to make a class but have [], +, *, etc work on that class.

    Update:  Here's why you use the &:

    Imagine that you didn't, and you have the code:

    myInstanceOfMyClass[4] = 1;

    If you didn't have the & then it would create a new int and set it to 1.  It would be the same as:

    int x = myInstanceOfMyClass[4];

    x = 1;

    ...and obviously that wouldn't change the value of myInstanceOfMyClass[4].

    But with the ampersand, when we assign to it, it's actually assigning to the int that's in your instance of your class.  So it's more like:

    int* ptr = the address of myInstanceOfMyClass[4];

    *ptr = 1;

    In other words, using the ampersand makes it so that if the caller changes the value that's returned, those changes "stick".

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.