CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14
  1. #1
    Join Date
    Jun 2019
    Posts
    30

    [] Operator Overloading in C++

    Hi,

    I implemented one method for getting an element at given position.

    But I need the logic for the same method Wrapping with the [] operator, and Please help me how to call that particular operator function


    please help me ASAP

    thank u in advance

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,395

    Re: [] Operator Overloading in C++

    Quote Originally Posted by Raj90 View Post
    I implemented one method for getting an element at given position.

    But I need the logic for the same method Wrapping with the [] operator, and Please help me how to call that particular operator function
    Could you be a bit more specific?
    Victor Nijegorodov

  3. #3
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: [] Operator Overloading in C++

    Simple example:
    Code:
    class MyClass
    {
    public:
    
        const int & operator[](int  i) const { return x[i]; }
              int & operator[](int  i)       { return x[i]; }
    
        // other member functions
    
    private:
    
        int x[10];
    };

  4. #4
    Join Date
    Jun 2019
    Posts
    30

    Re: [] Operator Overloading in C++

    Quote Originally Posted by VictorN View Post
    Could you be a bit more specific?
    Hi Victor,

    I have the method called get()

    Code:
    	 const T &get(uint16_t index) const
            {
                if (index >= size_ || index < 0)//if array out of bound
                {
                    return 0;
                }
                else
                {
                    index = tail_ + index >= size_ ? (index + tail_) - size_ : tail_ + index;
                    return items_[index];
                }
            }
    so this method i have to wrap with [] operator, and tell me how to test that
    Last edited by 2kaud; June 17th, 2019 at 02:57 AM. Reason: Adedd code tags

  5. #5
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: [] Operator Overloading in C++

    Just replace get with operator[]. As this is already const, returning const you only need the const version of operator[].

    However, you have another problem - returning 0 as a ref. Returning a ref means that the item referenced has to 'exist' once the function has returned. In this case, the return item is temporary. Does this compile? A possible 'simple' fix could be:

    Code:
    const T& operator[](uint16_t index) const
    {
         static T empty {};
    
         if (index >= size_ || index < 0)  //if array out of bound
             return empty;
     
         index = tail_ + index >= size_ ? (index + tail_) - size_ : tail_ + index;
         return items_[index];
    }
    and the calling code simply tests the return value against T {}.

    The more correct c++ way, though, would be to raise an exception rather than a return value which has to be tested each time.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  6. #6
    Join Date
    Feb 2017
    Posts
    677

    Re: [] Operator Overloading in C++

    Quote Originally Posted by Raj90 View Post
    const T &get(uint16_t index) const
    {
    if (index >= size_ || index < 0)//if array out of bound
    [/code]
    Note that since index is unsigned it can never be negative, It means "index < 0" will never be true and can be removed.
    Last edited by wolle; June 17th, 2019 at 04:09 PM.

  7. #7
    Join Date
    Jun 2019
    Posts
    30

    Re: [] Operator Overloading in C++

    Quote Originally Posted by 2kaud View Post
    Just replace get with operator[]. As this is already const, returning const you only need the const version of operator[].

    However, you have another problem - returning 0 as a ref. Returning a ref means that the item referenced has to 'exist' once the function has returned. In this case, the return item is temporary. Does this compile? A possible 'simple' fix could be:

    Code:
    const T& operator[](uint16_t index) const
    {
         static T empty {};
    
         if (index >= size_ || index < 0)  //if array out of bound
             return empty;
     
         index = tail_ + index >= size_ ? (index + tail_) - size_ : tail_ + index;
         return items_[index];
    }
    and the calling code simply tests the return value against T {}.

    The more correct c++ way, though, would be to raise an exception rather than a return value which has to be tested each time.

    static T empty {};? Why we use static? How can we solve without using statics?

  8. #8
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: [] Operator Overloading in C++

    Code:
    const T& operator[](uint16_t index) const
    {
         index = tail_ + index >= size_ ? (index + tail_) - size_ : tail_ + index;
         return items_[index];
    }
    and let the caller test first for empty.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  9. #9
    Join Date
    Jun 2019
    Posts
    30

    Re: [] Operator Overloading in C++

    Quote Originally Posted by 2kaud View Post
    Code:
    const T& operator[](uint16_t index) const
    {
         index = tail_ + index >= size_ ? (index + tail_) - size_ : tail_ + index;
         return items_[index];
    }
    and let the caller test first for empty.
    It should check that condition-- Array out of bounds?
    My test case is failing if i won't check that condition

  10. #10
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: [] Operator Overloading in C++

    We've had this discussion previously re return values and checking (http://forums.codeguru.com/showthrea...r-Buffer-POP()). Given your function definition, you either don't test or test and return an empty value. As you are returning a ref, you have to return something that exists after the function terminates - so just returning T{) won't do as this is a temporary. Hence static T empty{} and return empty. As empty is static, it exists after the function terminates so can be returned via a ref. Comments re not returning T{} etc etc are as per the other thread.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  11. #11
    Join Date
    Jun 2019
    Posts
    30

    Re: [] Operator Overloading in C++

    Quote Originally Posted by 2kaud View Post
    We've had this discussion previously re return values and checking (http://forums.codeguru.com/showthrea...r-Buffer-POP()). Given your function definition, you either don't test or test and return an empty value. As you are returning a ref, you have to return something that exists after the function terminates - so just returning T{) won't do as this is a temporary. Hence static T empty{} and return empty. As empty is static, it exists after the function terminates so can be returned via a ref. Comments re not returning T{} etc etc are as per the other thread.
    In case of functions returning a reference we need to return a reference to something which exists after function returns - otherwise it might crash. You used statics which keep existing after function exits. However there will be 1 static per type - no matter how many object you have. When if you have 2 buffers. And with one you want to return value 0 as default and with another value 1 as default. And both buffers are of exactly the same type. Doing that with statics will not work because if you set in a class static value to 0 it will be 0 for both objects. How could it be solved?

  12. #12
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: [] Operator Overloading in C++

    Then either:

    1) You need some way for the caller to indicate the default return value for an error (either as part of the function def or as part of the template def)

    2) You have different function(s) with different default return values.

    I don't know what type T is (and is probably defined by the caller for the template), but the default error return value has to be a valid value for the return type. That's why T {} is used as this is valid for all types. What if you have a type of std::string? T{} is still valid, but T{1} isn't.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  13. #13
    Join Date
    Jun 2019
    Posts
    30

    Re: [] Operator Overloading in C++

    Quote Originally Posted by 2kaud View Post
    Then either:

    1) You need some way for the caller to indicate the default return value for an error (either as part of the function def or as part of the template def)

    2) You have different function(s) with different default return values.

    I don't know what type T is (and is probably defined by the caller for the template), but the default error return value has to be a valid value for the return type. That's why T {} is used as this is valid for all types. What if you have a type of std::string? T{} is still valid, but T{1} isn't.

    T is template , type typename which supports all data types... I tested with all types. but when i have to return the value when the queue is empty,as of now i am returning T{} which is static , but without using static is there any other option?

  14. #14
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: [] Operator Overloading in C++

    Quote Originally Posted by Siddhi Patel View Post
    Hello, may u stuck at the operator overloading point so this is example may be help you..

    [] Operator Overloading in C++

    Code:
    class MyClass
    {
    public:
    
        const int & operator[](int  i) const { return x[i]; }
              int & operator[](int  i)       { return x[i]; }
    
        // other member functions
    
    private:
    
        int x[10];
    };
    which is an exact copy of Philips' post #3!! - so why post again??
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured