Search code examples
c++functionclassmember

In C++ is it possible to return an element of the class from a class member function?


In C++ is it possible to return an element of the class from a class member function?

namespace translation2d
{
    class translation2d
    {
        public:
           double x;
          double y;

        public:
            translation2d()
            {
                x=0;
                y=0;
            }

        public:
            translation2d translateBy(translation2d other); 
            //being interpreted as a constructor?
    }

    translation2d translation2d::translateBy(translation2d other)
    {//I need this member function to return an object of type translation2d
        x+=other.x;
        y+=other.y;
    }
};

Solution

  • 6502's answer is correct, and the code is neat.

    I just wanted to give a fix that minimises changes to your original code, for clarity:

    translation2d translation2d::translateBy(translation2d other)
    {
        translation2d copy = *this;
    
        copy.x += other.x;
        copy.y += other.y;
    
        return copy;
    }
    

    The idea is to:

    1. Create a copy of the "current" object so you don't impact the original (you don't want that)
    2. Return that copy once you've adjusted it with data from other

    Written another way, we can avoid copying the argument again since you already passed it by value:

    translation2d translation2d::translateBy(translation2d copy)
    {
        copy.x += this->x;
        copy.y += this->y;
    
        return copy;
    }
    

    … though I'd expect the compiler to do this for you in reality, and I find this version of the code harder to read. See the last section of this answer for other ways to avoid the extra copy (assuming that you are inclined to worry about it).


    An alternative version of this function would actually translate the current object rather than returning a new one:

    translation2d& translation2d::translateBy(translation2d other)
    {
        this->x += other.x;
        this->y += other.y;
    
        return *this;
    }
    

    Notice that I still return something, rather than void; in this case I've followed the convention of returning a reference to the current object, which aids in chaining multiple modifications to the same object. You'll find this pattern a lot in operator overloading.

    Technically the this-> is unnecessary, but it makes the function a bit easier to understand.


    Note that 6502 changed the function to take other by const-reference, which is often a good idea and you should consider doing that too (though copying two doubles is so cheap that it may not be worth the indirection).