Modifying Default Algebra Functions

This is a discussion on Modifying Default Algebra Functions within the C++ Programming forums, part of the General Programming Boards category; I want to know how to modify the default addition property of a class. For example, if I were to ...

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    26

    Modifying Default Algebra Functions

    I want to know how to modify the default addition property of a class. For example, if I were to create a class Complex, then the addition goes by adding the real components and the imaginary components. Suppose I have two complex numbers z1 and z2. I'd like it such that whenever I put: function (z1+z2) (here function is anything cout, return, parameter...). Then it would automatically use this addition rule, defined perhaps in the class.
    I know a little Python, and it's very easy there, you just have to put:
    def __add__(x,y): (the general way, not specifically this case)
    return x + y
    def __mult__(x,y):
    return x*y

    I wonder how to do this in C++.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    It is called operator overloading. You have to overload operator+.

  3. #3
    Registered User
    Join Date
    Oct 2006
    Posts
    26
    Ok thanks a lot

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Is it legal to have functions within functions?
    By Programmer_P in forum C++ Programming
    Replies: 13
    Last Post: 05-26-2009, 12:21 AM
  2. member as default argument
    By MarkZWEERS in forum C++ Programming
    Replies: 2
    Last Post: 03-23-2009, 09:09 AM
  3. Help with default parameter value using ptr-to-functor
    By registering in forum C++ Programming
    Replies: 2
    Last Post: 03-24-2004, 04:21 PM
  4. Switching Default Buttons :: MFC
    By kuphryn in forum Windows Programming
    Replies: 2
    Last Post: 07-02-2002, 05:08 PM
  5. Passing data/pointers between functions #2
    By TankCDR in forum C Programming
    Replies: 1
    Last Post: 11-02-2001, 09:49 PM

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