C++ recap: friend functions and operators overload

Friends

A friend function is a function that can access the private members of a class as though it were a member of that class. Example:

#include <iostream>

class Value {
private:
  int value;
  friend bool isEqual(const Value &v1, const Value &v2);

public:
  Value(int v) { value = v; }
};


bool isEqual(const Value &v1, const Value &v2) {
  return (v1.value == v2.value);
}


int main() {
  
  Value first(1);
  Value second(1);
  
  std::cout << isEqual(first, second) << std::endl;
  return 0;
}

Note that I need to supply to the function the object I want to work with, since there is no this pointer to do that for me.

Operators overload

Operators are defined as functions. Thus, x + y actually translates into operator+(x, y) and since I can overload functions, I can overload operators too :)

This is the dummy string library example with the + operator overloaded.

#include <iostream>
#include <cstring>

class myString 
{
private:
  char *string;
  int length;

public:
  myString(const char *new_string) {
    length = strlen(new_string) + 1;
    string = new char[length];
    strncpy(string, new_string, length);
    string[length -1] = '\0';
  }

  ~myString() {
    delete string;
    string = NULL;
  }

  // getters
  char *getString() { return string; }
  int getLength() { return length; }

  // overloading +
  friend myString operator+(myString &s1, myString &s2);  
  friend myString operator+(myString &s1, const char *s2);
};


int main() 
{
  using namespace std;

  myString s1("q");
  myString s2("p");
  myString s3 = s1 + s2;
  myString s4 = s3 + "!";

  cout << s4.getString() << endl;

  return 0;
}

// overloading myString + myString 
myString operator+(myString &s1, myString &s2) {

  char *combined = strcat(s1.getString(), s2.getString());
  return myString(combined);
}

// overloading myString + char* 
myString operator+(myString &s1, const char *s2) {

  char *combined = strcat(s1.getString(), s2);
  return myString(combined);
}

In a similar fashion it is possible to overload the output operator. Note that cout is an object of type ostream.

#include <iostream>
using namespace std;

class Something {
private:
  int a, b, c;
public:
  Something(int aa = 0, int bb = 0, int cc = 0) {
    a = aa;
    b = bb;
    c = cc;
  }

  friend ostream& operator<< (ostream &out, Something &sth);
};


ostream& operator<< (ostream &out, Something &sth) {
  out << "-> " << sth.a << endl
      << "-> " << sth.b << endl
      << "-> " << sth.c << endl;
  return out;
}


int main() {

  Something obj(1,2,4);
  cout << obj << endl;

  return 0;
}
|