Function and Operator Overloading in C++

Function and Operator Overloading in C++

Function Overloading:

Function Overloading is a programming concept whereby a function can be reused with different arguments and return type.

Eg. void print(char* szMessage) and void print(int number)

Operator Overloading:

Operator Overloading is a programming concept whereby existing operators can be overloaded so that when these operators are used with class objects, the operators have meaning appropriate to the new types.

For example:

class NumberClass {

public:

//Overloading the assignment operator
const NumberClass& operator=(const NumberClass &);

private:
  int a;
  int b;
  int c;
  
};
  
const NumberClass& NumberClass::operator=(const NumberClass& source)
{
  a = source.a;
  b = source.b;
  c = source.c;
  
  return *this;
}
  
main()
{
  NumberClass A(1,1,1), B(2,2,2);
  A=B; // Invoked the overloaded assignment function
  return 0;
}        

In the above example, the assignment operator is being overloaded with a new implementation within the class “NumberClass”.

Virtual function:

A virtual function is a member function that is declared in a base class that can be overridden by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the method.

Example :

class Base 
public:
  virtual void print() { cout << “\nThis is from Base Class” << endl; }
};
  
class Derive : public Base {
public:
  void print() { cout << “\nThis is from Derive Class” << endl; }
};
  
main() {
    Base* GenericClass = 0;
    GenericClass = new Derive;
    GenericClass->print();
    delete GenericClass;
}        

The above code snippets will invoke the derived class version of print().

Pure Virtual function

- A virtual function which has no implementation.

- Written as virtual prototype = 0;

- All derived class must provide their own definition.

- An abstract class is a class that contains pure virtual function.

Conclusion:

Function and operator overloading are important programming concepts in object-oriented programming languages that offer great flexibility to programmers if used correctly. In this article, I am using C++ for examples, but the same concepts can be applied to different languages like Java and C#.

To view or add a comment, sign in

Explore content categories