fleshbender
fleshbender

Reputation: 101

Helper function declaration outside class?

I came across a book which states that there are some functions called helper functions which are generally declared outside a class and contain some functionality that is repeatedly used in program.

They said == and != are types of helper functions that are used for comparisons of classes.

Why are they declared outside class?? I don't get the idea??

Upvotes: 0

Views: 726

Answers (1)

Maroš Beťko
Maroš Beťko

Reputation: 2329

If I understood you right, you are talking about friend functions. Operator== and operator != can be written outside the class body and their purpose is overloading == and != operators for your class so you cam compare them in if/while etc. statements. For example:

class A {
   int size;
public:
   A(int x) : size(x) {}; 
   // declaring that this operator can access private methods and variables of class A
   friend operator==(const A&, int);
   friend operator==(const A&, const A&); 
}

// overloaded operator for comapring classes with int
bool operator==(const A& lside, int rside) {
   return lside.size == rside;
}

// second overload for comapring structure two classes
bool operator==(const A& lside, const A& rside) {
   return lside == rside.size; // we can also use first operator
}

int main() {
   A obj(5);
   if (A == 5) { ... } // TRUE
   if (A == 12) { ... } // FALSE
}

If that's not what you meant, than there could also be a classic non-member function that any class can use. This could, as you said, be useful for functions that are used in multiple parts of your program not tied to any specific class. For example:

// simple function returnig average of given numbers from vector
int average(const std::vector<int>& vec) { 
   int sum = 0;
   for (int i : vec)
      sum += i;
   return sum / vec.size();
}

Upvotes: 2

Related Questions