Overloading Through Member Functions in C++

 Overloading Through Member Functions

When overloading is done inside a class, using non-static member functions, it is called overloading through member functions.

 

Inside the same class

Define multiple member functions with the same name but different parameter lists.

 

Resolved at compile time

The compiler checks which version matches the function call based on the number and type of arguments (early binding).

 

Syntax:

returnType operator+(ClassName obj);

 

Example :- Using Member Function

#include <iostream>

using namespace std;

 

class Complex {

    int real, img;

 

public:

    Complex(int r=0, int i=0) {

        real = r;

        img = i;

    }

 

    // Operator Overloading (Member)

    Complex operator + (Complex c) {

        Complex temp;

        temp.real = real + c.real;

        temp.img = img + c.img;

        return temp;

    }

 

    void display() {

        cout << real << " + " << img << "i" << endl;

    }

};

 

int main() {

    Complex c1(2,3), c2(4,5);

    Complex c3 = c1 + c2;

 

    c3.display();

}

 

Output:-

6 + 8i

 

Summary

Overloading happens at compile time →:- static polymorphism.

Return type does not play a role:- Two functions cannot differ only in return type.

Overloading is a feature of polymorphism in C++.

Overloading inside a class = member function overloading

(not operator overloading—different concept)


Post a Comment

0 Comments