-1

For a class like this:

class Foo {
  public:
    virtual int GetA();
    virtual int GetB();
};

Where should I declare a non-virtual function GetSumOfAB()?

1 - Make it an instance method?

class Foo {
  public:
    virtual int GetA();
    virtual int GetB();

    int GetSumOfAB() {
        return GetA() + GetB();
    }
};

2 - Make it a static method so it was obvious it is related to the class Foo?

class Foo {
  public:
    virtual int GetA();
    virtual int GetB();

    static int GetSumOfAB( Foo& foo ) {
        return foo.GetA() + foo.GetB();
    }
};

3 - Or make it a free function?

namespace Bar {
    int GetSumOfAB( Foo& foo );
}

What do you think?

EDIT:

I received a lot of strange downvotes, so I would like to clarify what the problem is.

GetSumOfAB() is an algorithm which uses public API of the class. There could be a lot of algorithms. Should I put all of them into the class as instance methods? Or should I prefer not to make my class large?

  • 5
    Do you have better example code? This code, frankly, doesn't do anything useful, so it's difficult to offer an opinion with respect to its implementation. – Robert Harvey May 19 '17 at 19:46
  • 2. Why would you make a static method if it needs an instance to operate on? That's the whole point of an instance method... – Alexander May 19 '17 at 22:36
  • Note that in C++ there are no "methods" at all. It's called member functions: stackoverflow.com/a/8596481/1116364 – Daniel Jour May 20 '17 at 2:23
  • The example is a bit bare but from an OOP perspective it can be seen as a collection of amounts with a Total property. That would make the first option the most appropriate one. – Martin Maat May 20 '17 at 4:25
  • @DanielJour I fail to see the difference. Structured blocks of code that take parameters, one of which is the instance it was called on, that potentially returns a value. – Alexander May 20 '17 at 6:37
2

Make it a non-member function.

If a function can be implemented as a non-member function, it should be implemented as a non-member function.

See this rather long and elaborate article by Scott Meyers that explains How Non-Member Functions Improve Encapsulation.

2

I would most certainly go with the first option.

The second option is nonsensical, the whole point of a class method is that it's not dependent on any particular instance of the class. A method that operates on a particular instance is exactly what an instance method is. Just use that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.