Operator overload

This is a discussion on Operator overload within the C++ Programming forums, part of the General Programming Boards category; Hi Just fooling around with operator overload to get used to the syntax. I cant find out why does this ...

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    162

    Operator overload

    Hi
    Just fooling around with operator overload to get used to the syntax.
    I cant find out why does this not work

    Code:
    class pet
    {
    private:
            int m_iAge;
    public:
          pet(int age);
          ~pet();
    
          pet operator+ (pet &);
    };
    
    pet pet::operator+ (pet & ptr)
    {
    	return pet(m_iAge + ptr.GetAge());
    }
    
    int main()
    {
        both = dog + cat;
        return 0;
    }
    Please help me

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,302
    You did not declare the (presumably) pet objects named dog, cat and both. There is no member function named GetAge.

    Actually, a member operator+ should be:
    Code:
    pet pet::operator+ (const pet & ptr) const
    {
    	return pet(m_iAge + ptr.GetAge());
    }
    It is probably better to implement a member operator+= and then implement a free function operator+ in terms of that. Of course, adding pets may not necessarily make sense, but I suppose if you're just testing the syntax out it is okay.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    It seems that you don't have a GetAge method.

    Neither have you declared pet objects called both, dog and cat.

    (Overloading + in this situation doesn't make much sense: now you would have a pet object that represents "both". Have you seen any such pet?)
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,020
    Two additional suggestions:
    Don't leave out argument names in class definitions or in function declarations.
    And "ptr" may be a misleading name for the argument since it's a reference, really, and not a pointer.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

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