HashTableView
HashTableView

Reputation: 13

C++ methods in object or static

So C++ supports object orientation but doesn't force one to use it. And lets make an example: We have a class Fruit with some complex data in it. And we want to calculate the calories

Option 1: We put the method directly in the class: public: int calculateCalories();

Option 2: We put it in Fruit.cpp but not in the class itself: int calculateCalories(Fruit f);

-> What is considered to be better pratice?

Upvotes: 1

Views: 64

Answers (1)

R Sahu
R Sahu

Reputation: 206607

What is considered to be better pratice?

If a function can be implemented as a non-member function using the existing public member functions of the class, it is better to make it a non-member function.

See How Non-Member Functions Improve Encapsulation if you can find some time. It's a bit lengthy.

Simple example:

class Circle
{
   public:
      Circle(double r = 0) : radius(r) {}

      double getRadius() const { return radius; }

   priviate:
      double radius;
};

Given the above, it is possible to implement functions to compute the area and circumference of a circle using non-member functions.

double area(Circle const& c)
{
   double r = c.getRadius();
   return M_PI*r*r;
}

double circumference(Circle const& c)
{
   double r = c.getRadius();
   return 2*M_PI*r;
}

According to the above article, it is better to implement these functions as non-member functions since they can be implemented using the existing public interface of Circle.

Upvotes: 4

Related Questions