Overloading Short-hand Operators and using friend functions




This video tutorial explains how to overload short-hand operators such as += and -= and also how to overload operators using friend function in c++ programming.
You will learn what is the difference between defining operator functions as class member and as a friend function, how to overload += and -= shorthand operators, how to define operator functions when we use friend functions in detail with examples.

source code for this tutorial

#include <iostream>

using namespace std;

class Marks{
int mark;
public:
    Marks(){
    mark = 0;
    }
    Marks(int m){
    mark = m;
    }
    void YourMarkPlease(){
    cout << "your mark is "<<mark<<endl;
    }

    void operator+=(int bonusmark){
    mark = mark + bonusmark;
    }

    friend void operator-=(Marks &curObj, int redmark);

};

void operator-=(Marks &curObj, int redmark){

curObj.mark -= redmark;
}

int main()
{
    Marks anilsmark(45);
    anilsmark.YourMarkPlease();

    int x = 20;

    anilsmark += x;
    anilsmark.YourMarkPlease();

    anilsmark -= x;
    anilsmark.YourMarkPlease();

    return 0;
}

 
Back To Top